How to create background video in react js?

Hi Friends πŸ‘‹,

Welcome To aHoisting!

To create background video in react js, you can set <source src="./earth.mp4" type="video/mp4"/> in <video>. It will create background video in react js.

Today, I am going to show you, how to create background video in react js.

Table of contents

  • Install and create a new React app.
  • Import react component.
  • Create a Component.

Let’s start with the first step.

Step 1: Install and create a new React app.

First you have to install the React project. You should use create-react-app command to create a new React project.

npx create-react-app my-app
cd my-app
npm start

Step 2: Import react component.

After installing, you have to import your React component.

import React from 'react';
import BackgroundVideo from './BackgroundVideo';

Step 3: Create a Component.

You can use src="./earth.mp4" to create background video in react js.

<div className="video-container">
  <video autoPlay loop muted className="background-video">
    <source src="./earth.mp4" type="video/mp4" />
      Your browser does not support the video tag.
    </video>
    <div className="overlay-content">
      {/* Your content goes here */}
      <h1>Welcome to My Site</h1>
      <p>This is a sample text over the video.</p>
  </div>
</div>

Create background video example.

The below code is an example of a React. You have to import react and set <source src="./earth.mp4" type="video/mp4" /> in <video> to create background video in react js.

App.js

import React from 'react';
import BackgroundVideo from './BackgroundVideo';

const App = () => {
  return (
    <div className="App">
      <BackgroundVideo />
    </div>
  );
};

export default App;

App.css

.video-container {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.background-video {
  position: absolute;
  top: 50%;
  left: 50%;
  width: auto;
  height: 100%;
  min-width: 100%;
  min-height: 100%;
  transform: translate(-50%, -50%);
  z-index: -1;
}

.overlay-content {
  position: relative;
  z-index: 1;
  color: white;
  text-align: center;
  padding-top: 30vh;
}

BackgroundVideo.js

import React from 'react';
import './App.css'; // Import styles

const BackgroundVideo = () => {
  return (
    <div className="video-container">
      <video autoPlay loop muted className="background-video">
        <source src="./earth.mp4" type="video/mp4" />
        Your browser does not support the video tag.
      </video>
      <div className="overlay-content">
        {/* Your content goes here */}
        <h1>Welcome to My Site</h1>
        <p>This is a sample text over the video.</p>
      </div>
    </div>
  );
};

export default BackgroundVideo;

In the above code example, I have used the <source src="./earth.mp4" type="video/mp4" /> to create background video in react js.

Check the output of the above code.

React, create, background, video

All the best πŸ‘