I am having a hard time setting a ref within a context provider. Is this not possible or is there something I am missing? I am able to createRefs in other components the same way but the following always shows the ref as { current: null }
const VideoPlayerContext = React.createContext();
export default class VideoPlayerProvider extends Component {
videoPlayerComponent = React.createRef()
state = {
// some state
}
seek = (time) => {
this.videoPlayerComponent.seek(time)
}
render () {
return (
<VideoPlayerContext.Provider value={Object.assign({}, this.state, { seek: seek})}><VideoPlayerkey={'videoplayer'}
{...this.state}
ref={this.videoPlayerComponent}
/>
{ this.props.children }
</VideoPlayerContext.Provider>
)
}
}
and then my app is wrapped with that as such
const app = () => (
<VideoPlayerProvider><App /></VideoPlayerProvider>
)
Any help appreciated!
It looks like you are trying to access the ref in the seek method with this.videoPlayerComponent.seek(time), but the videoPlayerComponent ref is defined as this.videoPlayerComponent = React.createRef(). You can access the current value of the ref by using this.videoPlayerComponent.current.seek(time).
Additionally, in your value prop for the VideoPlayerContext.Provider, you are using seek: seek instead of seek: this.seek. This would cause an error because seek is not defined in the scope. You should use seek: this.seek instead to correctly pass the seek method from the VideoPlayerProvider to the context value.
Here is the updated code:
export default class VideoPlayerProvider extends Component { videoPlayerComponent = React.createRef(); state = { // some state }; seek = (time) => { this.videoPlayerComponent.current.seek(time); }; render() { return ( <VideoPlayerContext.Provider value={Object.assign({}, this.state, { seek: this.seek })} > <VideoPlayer key={"videoplayer"} {...this.state} ref={this.videoPlayerComponent} /> {this.props.children} </VideoPlayerContext.Provider> ); } }