JojoD
JojoD

Reputation: 373

how to play/pause video in React without external library?

I have a video tag () in my webpage, and a "play/pause" button that when the user clicks on it, the video starts/stops playing . How can I do so in react if I'm not allowed to use js in order to call "getElementById" and then to use play()/pause() build-in methods. Any idea?

Upvotes: 33

Views: 94890

Answers (6)

Shahnur Alam Raju
Shahnur Alam Raju

Reputation: 21

import React, { useRef, useState } from 'react';

export const Video = () => {
    const videoRef = useRef();
    const [stop, setStop] = useState(false);

    const handleVideo = () => {
        setStop(!stop);
        if (stop === true) {
            videoRef.current.pause();
        } else {
            videoRef.current.play();
        }
    };

    return (
        <div onClick={handleVideo}>
            <video ref={videoRef} poster={HeroImg} controls>
                <source src={coverVideo} type="video/mp4" />
            </video>
        </div>
    );
};

Upvotes: 2

Codemaker2015
Codemaker2015

Reputation: 1

Use ref attribute to create a link to the video and using that reference we can able to use video controls on the video component

Try this code,

import React from "react";
class VideoDemo extends React.Component {
  
  getVideo = elem => {
    this.video = elem
  }

  playVideo = () => {
    this.video.play()
  };

  pauseVideo = () => {
    this.video.pause();
  };

  render = () => {
    return (
      <div>
        <video
          ref={this.getVideo}
          src="http://techslides.com/demos/sample-videos/small.mp4"
          type="video/mp4"
        />

        <div>
          <button onClick={this.playVideo}>
            Play!
          </button>
          <button onClick={this.pauseVideo}>
            Pause!
          </button>
        </div>
      </div>
    );
  };
}

export default VideoDemo;

Upvotes: 1

Wallace Sidhr&#233;e
Wallace Sidhr&#233;e

Reputation: 11597

This answer adds to @mheavers, which I upvoted.

There are a few differences:

  • One can pass noControls as a prop to the Video component, and apply the click event only if the <video> doesn't have the default controls (which will be the case when noControls is passed).
  • The handler function is a toggler; enabling one to play or pause according to its current state.
  • One can create a play button overlay style through the class video__play-button, whilst the same handler hides it through the class is-playing.
  • It also shows how to use two or more ref and pass them as a parameter to a pure render function.
import React, { useRef } from 'react';
import PropTypes from 'prop-types';

const renderVideo = ({
  noControls,
  src,
  vidButtonRef,
  vidRef,
  handleToggleVideo,
}) => (
  <>
    {noControls ? (
      <div ref={vidButtonRef} className="video video__play-button">
        <video
          ref={vidRef}
          src={src}
          onClick={handleToggleVideo}
        ></video>
      </div>
    ) : (
      <video
        src={src}
        controls
        controlsList="nodownload"
      ></video>
    )}
  </>
);

const Video = props => {
  const vidRef = useRef(null);
  const vidButtonRef = useRef(null);
  const { noControls, src } = props;
  const handlePlay = () => {
    vidRef.current.play();
    // hide overlay play button styles, set by 'video__play-button'
    vidButtonRef.current.classList.add('is-playing');
  };
  const handlePause = () => {
    vidRef.current.pause();
    // show overlay play button styles, set by 'video__play-button'
    vidButtonRef.current.classList.remove('is-playing');
  };
  const handleToggleVideo = () => (vidRef.current.paused ? handlePlay() : handlePause());
  return (
    <>
      {renderVideo({
        noControls,
        src,
        vidButtonRef,
        vidRef,
        handleToggleVideo,
      })}
    </>
  );
};

Video.propTypes = {
  noControls: PropTypes.bool,
  videoUrl: PropTypes.string,
};

export default Video;

Upvotes: 4

mheavers
mheavers

Reputation: 30158

Updated example for React Function Components:

import React, { useRef} from 'react'

function myComponent(props) {
  const vidRef = useRef(null);
  const handlePlayVideo = () => {
    vidRef.current.play();
  }
  return (
    <video ref={vidRef}>
      <source src={[YOUR_SOURCE]} type="video/mp4" />
    </video>
  )
}


Upvotes: 40

Brad Colthurst
Brad Colthurst

Reputation: 2605

The most straightforward way would be to use refs which is a React feature that will let you invoke methods on the component instances that you have returned from a render().

You can read up a little more on them in the docs: https://facebook.github.io/react/docs/more-about-refs.html

In this case just add a ref string to your video tag like so:

<video ref="vidRef" src="some.mp4" type="video/mp4"></video>

That way when you add click handlers to your buttons:

<button onClick={this.playVideo.bind(this)}>PLAY</button>

The playVideo method will have access to your video reference through refs:

playVideo() {
  this.refs.vidRef.play();
}

Here is a working DEMO so you can check out a full example.

Upvotes: 25

Hitesh Sahu
Hitesh Sahu

Reputation: 45072

Accepted answer was using old react style, if you want to do with ES6

A simple component to auto play pause along with manual controls playing Polestar intro:

    import React from "react";
    class Video extends React.Component {
      componentDidMount = () => {
        this.playVideo();
      };

      componentWillUnmount = () => {
          this.pauseVideo();
      };


      playVideo = () => {
        // You can use the play method as normal on your video ref
        this.refs.vidRef.play();
      };

      pauseVideo = () => {
        // Pause as well
        this.refs.vidRef.pause();
      };

      render = () => {
        return (
          <div>
            <video
              ref="vidRef"
              src="https://assets.polestar.com/video/test/polestar-1_09.mp4"
              type="video/mp4"
            />

            <div>
              <button onClick={this.playVideo}>
                Play!
              </button>
              <button onClick={this.pauseVideo}>
                Pause!
              </button>
            </div>
          </div>
        );
      };
    }

 export default Video;

Video from https://www.polestar.com/cars/polestar-1

Upvotes: 8

Related Questions