Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

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?

like image 966
JojoD Avatar asked May 26 '16 14:05

JojoD


People also ask

How play and pause video in react JS?

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 .

How do you pause other videos if selected video is playing in react?

You could store all player instances in a Context and use a Provider and Consumer to pause all players if one starts playing. Since you pass a playing boolean to ReactPlayer, you can easily store a id or reference of the current playing player.

How do you pause in react?

Take the reference of the audio file in ReactJS Using Audio Class. Set the default state of the song as not playing. Make a function to handle the Play/Pause of the song. Use the play() and pause() functions of audio class to do these operations.


2 Answers

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>
  )
}


like image 146
mheavers Avatar answered Oct 18 '22 02:10

mheavers


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.

like image 24
Brad Colthurst Avatar answered Oct 18 '22 03:10

Brad Colthurst