autoplayVideo.tsx 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import React from 'react';
  2. type Props = React.HTMLProps<HTMLVideoElement>;
  3. /**
  4. * Wrapper for autoplaying video.
  5. *
  6. * Because of react limitations and browser controls we need to
  7. * use refs.
  8. *
  9. * Note, video needs `muted` for `autoplay` to work on Chrome
  10. * See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video
  11. */
  12. class AutoplayVideo extends React.Component<Props> {
  13. componentDidMount() {
  14. if (this.videoRef.current) {
  15. // Set muted as more browsers allow autoplay with muted video.
  16. // We can't use the muted prop because of a react bug.
  17. // https://github.com/facebook/react/issues/10389
  18. // So we need to set the muted property then trigger play.
  19. this.videoRef.current.muted = true;
  20. const playPromise = this.videoRef.current.play();
  21. // non-chromium Edge and jsdom don't return a promise.
  22. playPromise?.catch(() => {
  23. // Do nothing. Interrupting this playback is fine.
  24. });
  25. }
  26. }
  27. private videoRef = React.createRef<HTMLVideoElement>();
  28. render() {
  29. const {className, src, ...props} = this.props;
  30. return (
  31. <video
  32. className={className}
  33. ref={this.videoRef}
  34. playsInline
  35. disablePictureInPicture
  36. loop
  37. {...props}
  38. >
  39. <source src={src} type="video/mp4" />
  40. </video>
  41. );
  42. }
  43. }
  44. export default AutoplayVideo;