javascriptreactjsreact-player

How can I start a video at specific timestamp in React?


Here is my component and I want to automatically play it from a certain time like 00:07:12,600, not from the start.

import style from './Hero.module.css';
import Image from 'next/image';
import ReactPlayer from 'react-player';
import { useState } from 'react';

export default function Index() {
  const [isPlaying, setIsPlaying] = useState(true);

  return (
    <div className={style.hero_container}>
      {/* <Image src="/images/hero/hero1.jpg" alt="Logo" height={400} width={700} /> */}

      <ReactPlayer
        url="/videos/Dexter.S01E03.1080p.5.1Ch.BluRay.ReEnc-DeeJayAhmed.mkv"
        playing={isPlaying}
        width="100%"
        height="100%"
        controls={true}
      />
    </div>
  );
}

Solution

  • Use the onReady event together with the seekTo method.

    Something like this

    const playerRef = React.useRef();
    
    const onReady = React.useCallback(() => {
      const timeToStart = (7 * 60) + 12.6;
      playerRef.current.seekTo(timeToStart, 'seconds');
    }, [playerRef.current]);
    
    <ReactPlayer
       ref={playerRef}
       url="/videos/Dexter.S01E03.1080p.5.1Ch.BluRay.ReEnc-DeeJayAhmed.mkv"
       playing={isPlaying}
       width="100%"
       height="100%"
       controls={true}
       onReady={onReady}
    />
    

    Update

    Looks like onReady is fired after each seek event so we need some extra logic.

      const [isPlaying, setIsPlaying] = React.useState(true);
      const [isReady, setIsReady] = React.useState(false);
      const playerRef = React.useRef();
    
      const onReady = React.useCallback(() => {
        if (!isReady) {
          const timeToStart = (7 * 60) + 12.6;
          playerRef.current.seekTo(timeToStart, "seconds");
          setIsReady(true);
        }
      }, [isReady]);