Skip to content
Related Articles

Related Articles

How to put an image as background under multiple components in ReactJS?
  • Last Updated : 19 Jan, 2021

We can make a parent component and use that parent component to wrap the child component so that the parent component appears as an image overlay above the child component.

Syntax:

<div style={{  
  backgroundImage: `url(${'/background.jpg'})`}}>
  {props.children}
</div>

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. folder name, move to it using the following command:



cd foldername

Project Structure: It will look like the following.

Filename-App.js:

Javascript




import { React, Component } from 'react'
import Parent from './Parent'
class App extends Component {
  
  render() {
    return (
      <Parent>
        <div>
          <h4 style={{
            color: 'black',
            height: 200,
            width: 200,
            padding: 50
          }}>
            This component has a background image
          </h4>
        </div>
      </Parent>
    )
  }
}
  
export default App

Filename-Parent.js:

Javascript




import React from 'react'
  
  
const Parent = (props) => {
    const URL = 
    return (
        <div style={{
            backgroundImage: `url(${URL})`,
            backgroundRepeat:'no-repeat',
            backgroundColor: 'lightblue',
        }}>
            {props.children}
        </div>
    )
}
  
export default Parent;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

My Personal Notes arrow_drop_up
Recommended Articles
Page :