Billy Noyes
Billy Noyes

Reputation: 113

Video not playing on mobile using React

anyone run into a similar issue like this where the video works on desktop but not on mobile?

<video className="app__backgroundVideo" autoplay="autoplay" loop="loop" muted>
          <source src={Video} type="video/mp4" />
          Your browser does not support the video tag.
</video>

Upvotes: 1

Views: 8309

Answers (2)

Marco Noto
Marco Noto

Reputation: 81

For anyone looking for a solution that won't use dangerouslySetInnerHTML, you may try this brilliant hooks based solution that I found after some frustrating hours (worked for me). Instead of directly using the HTML5 video tag, you should implement a custom component such that:

import React, {useRef, useEffect} from "react"

export default function AutoPlaySilentVideo(props) {
    const videoRef = useRef(undefined);
    useEffect(() => {
        videoRef.current.defaultMuted = true;
    })
    return (
        <video
            className={props.className}
            ref={videoRef}
            loop
            autoPlay
            muted
            playsInline>
            <source src={props.video} type="video/mp4"/>
        </video>
    );
}

You will use a video source as prop and eventually a className if you need it.

The issue is well known to the react community and for some reasons it has been remained (officially) unsolved in the last few years. The problem is that the muted property will not show up in the DOM as a node. You can read more about this here.

Upvotes: 7

Shamar Yarde
Shamar Yarde

Reputation: 760

Try the following:

<div
          dangerouslySetInnerHTML={{
            __html: `<video className="app__backgroundVideo" autoplay loop muted playsinline>
      <source src=${Video} type="video/mp4" />
      Your browser does not support the video tag.
</video>`,
          }}
        />

Explanation is mostly in the Medium link with more details. It looks like Safari has a problem with the muted attribute not being guaranteed to be set in the DOM which causes a problem when accessed using Safari. The medium link has more solutions should this not work. It worked for me.

References:

Medium. Autoplay muted HTML5 video using React on mobile (Safari / iOS 10+). https://medium.com/@BoltAssaults/autoplay-muted-html5-video-safari-ios-10-in-react-673ae50ba1f5. (Accessed 11 December, 2020)

Stack Overflow. React (HTML) video tag won't autoplay on mobile devices. https://stackoverflow.com/a/59418124/8121551. (Accessed 11 December, 2020)

Upvotes: 4

Related Questions