Home > Web Front-end > JS Tutorial > body text

React Basics~useRef/ video playing

DDD
Release: 2024-10-11 18:39:02
Original
251 people have browsed it
  • 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;

Copy after login

・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.

React Basics~useRef/ video playing

・This is a stopping action.

React Basics~useRef/ video playing

Sorry I can't show the action as video.

The above is the detailed content of React Basics~useRef/ video playing. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!