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

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.


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


Tags:

Reactjs