Open In App

How to put an image as background under multiple components in ReactJS with React Routing?

Last Updated : 06 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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 ,{Fragment} from 'react'
import { withRouter } from 'react-router-dom';

const Parent = (props) => {
    const URL = 
'https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg'
    return (
    <Fragment>
        <div style={{
            backgroundImage: `url(${URL})`,
            backgroundRepeat:'no-repeat',
            backgroundColor: 'lightblue',
        }}>
            {props.children}
        </div>
        </Fragment>
    )
}

export default withRouter(Parent);

 
Step : To wrap this component on top of Routing Switch Component as Sample

<Parent>

           <Switch>

             <Route path="/testpage" component={Test} />

             <Route path="/testpage1" component={Test1} />

        </Switch>

</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:


 


 


Next Article
Article Tags :

Similar Reads