trainReact.com
||

8. Video Player with Play/Pause Functionality

Medium
Category: Hooks
State ManagementuseRefuseStatevideo tag

React Video Player Challenge

Problem Description

The current PlayVideoWithButton component renders a video player with a play/pause button. However, the implementation is incomplete and has the following issues:

  1. The play/pause button doesn't actually control the video playback.
  2. The button text doesn't update to reflect the current state of the video (playing or paused).
  3. The component doesn't properly handle the video's play and pause states.
  4. The isPlaying state is not being used effectively.

Your Task

Your goal is to modify the PlayVideoWithButton component to create a fully functional video player with the following features:

  1. Clicking the play/pause button should start or stop the video playback.
  2. The button text should change between "Play" and "Pause" based on the current state of the video.
  3. The isPlaying state should accurately reflect whether the video is currently playing or paused.

Constraints

  • Do not change the overall structure of the component or the CSS classes used.
  • Do not change the data-testids implemented.
  • Do not change the current error management logic of the component.

Hints

  • Consider how you can use the useRef hook to interact with the video element directly.
import { useState, useRef } from 'react';
import './play-pause-video.css'

export default function PlayVideoWithButton() {
  const isPlaying = false;
  const [error, setError] = useState(null);

  if(error) {
    return <div data-testid="error-message">{error}</div>
  }

  return (
    <div className="video-container">
      <button
        data-testid="play-pause-button"
        className="play-button"
      >
        {isPlaying ? 'Pause' : 'Play'}
      </button>
      <video
        data-testid="video-player"
        className="video-player"
        controls
        onError={() => setError("Something went wrong loading the video!")}
      >
        <source
          src="https://sample-videos.com/video321/mp4/720/big_buck_bunny_720p_2mb.mp4"
          type="video/mp4"
        />
      </video>
    </div>
  )
}

Open browser consoleTests