Search code examples
javascriptreactjsvideoautoplay

Autoplay video in ReactJS don`t work with Chrome


I just created website with ReactJS and notised that video in main page doesnt starts playing in Chrome. It only starts playing when I go to different page and then go back to the main page. Does someone have any suggestions please? Somewhere I saw that they fixed it with JQuery, but I dont wanna add JQuery into the React until its really necessary.

I used video like this

<video src={Video} muted playsInline={true} autoPlay={true} loop disablePictureInPicture></video>

And also like this

<video playsInline loop disablePictureInPicture autoPlay muted>
    <source src={Video} type="video/mp4" />
</video>

Also the "muted" doesn't appear in dom.. In action it can be seen here: https://www.chiptuning-brno.cz/ Thank you very much.


Solution

  • So finally solution is to pass "muted" via ref like this:

    const videoRef = useRef(null)
    
      useEffect(() => {
        const { current: videoElement } = videoRef
        videoElement.setAttribute('muted', '')
      }, [])
    
    <video src={Video} ref={videoRef} playsInline autoPlay loop disablePictureInPicture muted />
    

    As I saw, it is known issue for few years and this solution is from here:

    https://github.com/facebook/react/issues/10389#issuecomment-605689475