1

I can't seem to be able to skip to a particular time using ReactPlayer.

Here's my code.

import React, { useRef } from "react";
import ReactPlayer from "react-player";

function VideoPlayer(props) {
  const { video, setCurrTime, setAddComment } = props;

  const playerRef = useRef();

  const writeComments = () => {
    if (playerRef.current) {
      setCurrTime(playerRef.current.getCurrentTime());
      setAddComment(true);
    }
  };

  return (
    <div className="player-wrapper">
      <ReactPlayer
        ref={playerRef}
        className="react-player"
        width="100%"
        height="100%"
        url={`http://127.0.0.1:8000${video.video}`}
        controls
        onPause={writeComments}
      />
    </div>
  );
}

export default VideoPlayer;

I suspect it might be the file format, MP4.

peanutsee
  • 100
  • 10

1 Answers1

0

Unfortunately playerRef doesn't get set to a value you can use.

First caveat: https://github.com/cookpete/react-player/issues/1508 This is an open issue about React's StrictMode often enabled on new projects for React 18. It breaks setting src on the player so it doesn't work. If you upgrade to React 18, the simplest but not ideal solution is to disable React.StrictMode.

If your player is loading, you're on React 17 or you are not using StrictMode.

So if your video is loading, use ReactPlayer's onReady to set your playerRef. player passed into your onReady handler is the actual instance of ReactPlayer which has the methods you are looking for.

import React, { useRef } from "react";
import ReactPlayer from "react-player";

function VideoPlayer(props) {
  const { video, setCurrTime, setAddComment } = props;

  const playerRef = useRef();

  const writeComments = () => {
    if (playerRef.current) {
      setCurrTime(playerRef.current.getCurrentTime());
      setAddComment(true);
    }
  };

  return (
    <div className="player-wrapper">
      <ReactPlayer
        className="react-player"
        width="100%"
        height="100%"
        url={`http://127.0.0.1:8000${video.video}`}
        controls
        onPause={writeComments}
        onReady={(player) => playerRef.current = player}
      />
    </div>
  );
}

export default VideoPlayer;

ReactPlayer player instance available in onReady

Michael Wills
  • 91
  • 2
  • 5