autoplayVideo.tsx 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import {useEffect, useRef} from 'react';
  2. interface AutoplayVideoProps extends React.VideoHTMLAttributes<HTMLVideoElement> {
  3. 'aria-label': string;
  4. }
  5. /**
  6. * Wrapper for autoplaying video.
  7. *
  8. * Because of react limitations and browser controls we need to
  9. * use refs.
  10. *
  11. * Note, video needs `muted` for `autoplay` to work on Chrome
  12. * See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video
  13. */
  14. function AutoplayVideo(props: AutoplayVideoProps) {
  15. const videoRef = useRef<HTMLVideoElement>(null);
  16. useEffect(() => {
  17. if (videoRef.current) {
  18. // Set muted as more browsers allow autoplay with muted video.
  19. // We can't use the muted prop because of a react bug.
  20. // https://github.com/facebook/react/issues/10389
  21. // So we need to set the muted property then trigger play.
  22. videoRef.current.muted = true;
  23. // non-chromium Edge and jsdom don't return a promise.
  24. videoRef.current.play()?.catch(() => {
  25. // Do nothing. Interrupting this playback is fine.
  26. });
  27. }
  28. }, []);
  29. return <video ref={videoRef} playsInline disablePictureInPicture loop {...props} />;
  30. }
  31. export {AutoplayVideo};