Adding a Video Background in React
A video background can be a nice way to add a little flash to your next website, and adding one couldn’t be easier.
The first step is (obviously) finding a video. Ideally it should be a short loop that’s not too heavy on bandwidth and doesn’t distract from the content of your page. If you happen to have access to video editing software, you can also make it a perfect loop by taking the clip you want to use, reversing it, and adding the reversed clip to the end of the original. Here’s one I put together in Premiere:
Once you have your video, you can add it to the assets folder of your project and build a simple React component for it. Mine looks like this. Note the attributes in my video tag — it’s a good idea to make sure your video is muted so the user doesn’t get blasted with sound when they open your page. We could also add a poster=”whateverImage.jpg” attribute so it displays an image while the video loads, or if it fails to load at all.
Once you have your video component built simply place it in the component you want to use it with and write your CSS:
I used object-fit: cover and set the width and height to match the viewport width and height so that it fills the screen. The rest is making sure it’s in the proper position. I also used z-index: -1 so that it displays behind our main content. If you have trouble getting your content to display over it, try adding z-index: 2 to whatever you want the user to see. Here’s what my final product looks like: