0

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

fay
  • 41
  • 8
  • Whatever you doing, I don't think you mean using `this` on function instance, I guess thats what breaks your code. I believe you tried to change code from class to function components. – Dennis Vash Aug 10 '22 at 12:04
  • @DennisVash yeah, I thought that was the issue, but then it worked on CodeSandbox. How do I do that ref with the player in a function then? – fay Aug 10 '22 at 13:29

1 Answers1

1

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

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118