DEV Community

Cover image for React Basics~useRef/ video playing
Ogasawara Kakeru
Ogasawara Kakeru

Posted on

React Basics~useRef/ video playing

  • The useRef is one of the react hooks that tracks the state of DOM elements.

  • We can also control the state of DOM elements using this hook.

・src/Example.js

import { useRef, useState } from "react";

const Video = () => {
  const [playing, setPlaying] = useState();
  const videoRef = useRef();

  return (
    <div>
      <video style={{ maxWidth: "100%" }} ref={videoRef}>
        <source src="./sample.mp4"></source>
      </video>
      <button
        onClick={() => {
          if (playing) {
            videoRef.current.pause();
          } else {
            videoRef.current.play();
          }
          setPlaying((prev) => !prev);
        }}
      >
        {playing ? "Stop" : "Play"}
      </button>
    </div>
  );
};

const Example = () => {
  return (
    <>
      <Video />
    </>
  );
};

export default Example;

Enter fullscreen mode Exit fullscreen mode

・We set a value of useRef as videoRef to the video element's ref attribute.

・When we press the button, we can control the video action using videoRef.current.pause() or videoRef.current.play() in the button's onClick function.

・This is a playing action.

Image description

・This is a stopping action.

Image description

Sorry I can't show the action as video.

Top comments (0)