Search code examples
reactjsreact-player

How to display a button on the video after video ends with react-player


In my React app, I want a button to navigate to the next lesson to be appeared on the video, right after the current video is finished playing. I'm using react-player to display videos. I want to know how can I accomplish this is react-player. Any helpful tip is highly appreciated.

 <ReactPlayer
          url={videoPath}
          width="100%"
          height='100%'
          controls={true}
          className="player"
          onEnded={markLessonAsCompleted}
          config={{
            file: {
              attributes: {
                controlsList: "nodownload"
              }
            }
          }}
          volume={1}
        />

Solution

  • You could set a boolean state value when the video ends (onEnded) and conditionally show the "next" button. The button needs to be absolutely positioned to overlay the video. And to center the button flex box is one of many options.

    The following code is also available here as a code sandbox.

    function App() {
      const urls = [
        'https://www.youtube.com/watch?v=oPZXk4ESdng?t=50',
        'https://www.youtube.com/watch?v=bcWZ6C-kn_Y'
      ]
      const [currentUrlIndex, setCurrentUrlIndex] = React.useState(0)
      const [showNextButton, setShowNextButton] = React.useState(false)
    
      return (
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center'
          }}
        >
          <ReactPlayer
            url={urls[currentUrlIndex]}
            playing
            controls
            onEnded={() => setShowNextButton(true)}
            style={{
              width: '100%',
              height: '100%'
            }}
          />
          {showNextButton && (
            <button
              onClick={() => {
                setCurrentUrlIndex(
                  prevUrlIndex => (prevUrlIndex + 1) % urls.length
                )
                setShowNextButton(false)
              }}
              style={{
                position: 'absolute',
                zIndex: 10,
                fontSize: '2em'
              }}
            >
              next
            </button>
          )}
        </div>
      )
    }