creating ref within react context provider
Asked Answered
D

0

8

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})}>
        <VideoPlayer 
          key={'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!

Disrate answered 8/11, 2018 at 19:18 Comment(3)
Look into forwardRef(): reactjs.org/docs/forwarding-refs.htmlPressurize
yea I was looking at that but it was not immediately clear to me why that would be neccessary here. I see it used with higher order components, but no examples within component.Provider, may just be misunderstanding when to use thoughDisrate
Is the VideoPlayer component defined as a class component?Soutache

© 2022 - 2024 — McMap. All rights reserved.