Reputation: 1285
In my react component I have a video tag like so:
<video>
<source src="https://fake.com/file.mp4" type="video/mp4" />
</video>
And I have a button a bit further down that I would like to use to activate the video:
<button onClick={playVideoFunc?}/>
I assume I will be using some sort of on click event to trigger the video play and I know I can use the following javascript code to do it:
var v = document.getElementsByTagName("video")[0];
v.play();
But sense this is my first time using react I was wondering if there was a more "reacty" way of doing this? Additionally if I do have to use pure javascript like above is it appropriate to put that code inside the react component itself? For reference my component looks like this (minus some details):
import React, { Component } from 'react';
import Footer from './footerComponent'
import Navbar from './navbarComponent';
class Home extends React.Component{
render() {
return (
<div className="wrapper home-page">
<div className="jumbotron-video-wrapper">
<video>
<source src="https://fake.com/file.mp4" type="video/mp4" />
</video>
</div>
<Navbar type={"transparent"}/>
<div className="jumbotron margin-bottom-20" style={heroStyle}>
<div className="container-fluid">
<div className="row">
<div className="col-md-8 col-md-offset-2 text-center">
<h1>WORDS WORDS WORDS</h1>
<img onClick={playvideo??} width="130" src={playImage}/>
<p className="thin">Watch our video</p>
</div>
</div>
</div>
</div>
<Footer/>
</div>
)
}
};
export default Home;
Upvotes: 6
Views: 16977
Reputation: 21
You can use the useRef hook to make a reference to the video. Then inside the onClick function you can play the video. You can do something like this.
The "Video" in the image is a styled-component of a video tag. FYI
Upvotes: 2
Reputation: 65
you could also do onClick={e => e.target.play()} on the video element. hope this helps
Upvotes: 3
Reputation: 28397
You can assign a ref to your video element and call play() using this.refs.video.play().
class Home extends React.Component{
render() {
return (
<div className="wrapper home-page">
<div className="jumbotron-video-wrapper">
<video ref="video">
<source src="https://fake.com/file.mp4" type="video/mp4" />
</video>
</div>
<Navbar type={"transparent"}/>
<div className="jumbotron margin-bottom-20" style={heroStyle}>
<div className="container-fluid">
<div className="row">
<div className="col-md-8 col-md-offset-2 text-center">
<h1>WORDS WORDS WORDS</h1>
<img onClick={() => {this.refs.video.play()}} width="130" src={playImage}/>
<p className="thin">Watch our video</p>
</div>
</div>
</div>
</div>
<Footer/>
</div>
)
}
};
Upvotes: 7