Hello, DEV community!
Today I was struggling with a video element in a react app. I was trying to insert an video to a website that would play looped in the background.
That would require adding autoPlay
, loop
and muted
attributes to the video tag like here:
// App.jsx //
import mutedVideo from './media/muted_vid.mp4'
import './App.css';
function App() {
return (
<div className="App">
{/* VIDEO */}
<video autoPlay muted loop>
<source src={mutedVideo} />
</video>
{/* //VIDEO */}
</div>
);
}
export default App;
For some reason during source code bundling, React keeps ignoring muted
attribute. So the final outcome in production looks like this:
After a while of research and browsing Stack Overflow, I learned that it is a common issue in React that still hasn't been solved for years!
I've also found a workaround solution to overcome this bug. The solution is creating my own Video
component:
// components/Video.jsx //
export default class Video extends Component {
state = {
html: "",
};
componentDidMount() {
const src = this.props.src;
const html = `
<video autoPlay muted loop>
<source src=${src} />
</video>
`;
this.setState({ html });
}
render() {
return <div dangerouslySetInnerHTML={{ __html: this.state.html }}></div>;
}
}
This component takse src
of a video as a prop and returns a <div>
with directly injected <video>
tag and it's attributes.
Here's App code with new Video component:
// App.jsx //
import mutedVideo from "./media/muted_vid.mp4";
import Video from "./components/Video";
import "./App.css";
function App() {
return (
<div className="App">
{/* VIDEO */}
<Video src={mutedVideo} />
{/* //VIDEO */}
</div>
);
}
export default App;
Now this gave me result that I expected in production output:
As an effect, the video can be easily played in the background.
IMPORTANT NOTE! dangerouslySetInnerHTML
is not called "dangerous" for no reason. Even though it is safe to use it in this particular case, in many other cases it should not be used unless you really know what you're doing :). Here is more detailed article about this property.
Did you happen to deal with such an issue? Please share your story in the comment section.
Happy coding!
Follow me on Twitter
Top comments (2)
Hey, I’m looking for a ninja technique to autoplay a video in React without it being muted. Can you help me with this, please?
Thanks for your work.
it was helpful to me because I had the same problem with a video to loop in my welcome page....
Good job!
Keep it up