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 t
This answer adds to @mheavers, which I upvoted.
There are a few differences:
noControls
as a prop to the Video
component, and apply the click event only if the
doesn't have the default controls (which will be the case when noControls
is passed).video__play-button
, whilst the same handler hides it through the class is-playing
.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 ? (
) : (
)}
>
);
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;