javascriptreactjsreact-hooksrefcodesandbox

ref for react-player works on codesandbox but breaks locally


I'm trying to make a player with my own controls, and as I was looking at the demo code for react-player, I saw I had to use ref to play the video from a certain place with a range input. Documentation here

In the demo app, ref is used in this way:

  ref = player => {this.player = player}

Then it's passed to the ReactPlayer component

   <ReactPlayer
       ref={this.ref}
       className='react-player'
          ...
    />

When I tried to do the same, it breaks, but as I was putting the code on CodeSandbox to submit it here as a question, I discovered it works perfectly.

Locally, I get this error: "Uncaught TypeError: Cannot set properties of undefined (setting 'player')" . What can I do to make it work locally just like it works on CodeSandbox? The code is absolutely the same, so I'm scratching my head here. Edit: Might be because it's using this in something that isn't a Class, but how do I do it in a function then? And why would it work in CodeSandbox?

Link to CodeSandbox / Link to what I have locally on Github


Solution

  • Follow React API and use useRef hook to handle refs.

    export default function FullPlayer() {
      const playerRef = useRef();
    
      const handleSeekMouseUp = (e) => {
        // ...
        playerRef.current.seekTo(parseFloat(e.target.value));
      };
    
      return (
        <div>
          <ReactPlayer
            ref={playerRef}
            className="react__player"
            url="https://www.youtube.com/watch?v=wp43OdtAAkM"
            playing={state.isPlaying}
            loop={true}
            played={state.played}
            controls={false}
          />
          {/*...*/}
        </div>
      );
    }
    

    Edit purple-shadow-u14kv0