Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why `muted` attribute on video tag is ignored in React?

Well, as counter-intuitive as it sounds, muted tag is somehow ignored; check out the snippet below, first one is rendered with react, the second one regular html; inspect them with your dev tools, and you see the react on doesn't have muted attribute; I already tried muted={true}, muted="true" but non is working.

function VideoPreview() {
  return (
    <div className="videopreview-container">
      React tag:
      <video
        className="videopreview-container_video"
        width="320"
        height="240"
        controls
        autoPlay
        muted
      >
        <source src="https://raw.githubusercontent.com/rpsthecoder/h/gh-pages/OSRO-animation.mp4" type="video/mp4" />
        Your browser does not support the video tag.
      </video>
    </div>
  );
}

ReactDOM.render(<VideoPreview />, root)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>


<div id="root"></div>


<hr/>
Regular html:
<video
  width="320"
  height="240"
  controls
  autoplay
  muted
>
  <source src="https://raw.githubusercontent.com/rpsthecoder/h/gh-pages/OSRO-animation.mp4" type="video/mp4" />
  Your browser does not support the video tag.
</video>
like image 705
Mhmdrz_A Avatar asked Apr 29 '20 19:04

Mhmdrz_A


2 Answers

This is actually a known issue which has existed since 2016. The video will be muted correctly, but the property will not be set in the DOM. You can find multiple workarounds in the GitHub issue, although there might be pros and cons with any of them.

like image 55
FluidSense Avatar answered Nov 03 '22 01:11

FluidSense


As mentioned by @FluidSense it is an open bug since forever.

I could achieve it like this:

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

export default function Video({ src, isMuted }) {
    const refVideo = useRef(null);

    useEffect(() => {
        if (!refVideo.current) {
            return;
        }

        if (isMuted) {
            //open bug since 2017 that you cannot set muted in video element https://github.com/facebook/react/issues/10389
            refVideo.current.defaultMuted = true;
            refVideo.current.muted = true;
        }

        refVideo.current.srcObject = src;
    }, [src]);

    return (
            <video
                ref={refVideo}
                autoPlay
                playsInline //FIX iOS black screen
            />
    );
}
like image 32
CodingYourLife Avatar answered Nov 02 '22 23:11

CodingYourLife