Thursday, January 16, 2025
Google search engine
HomeLanguagesHow to put an image as background under multiple components in ReactJS...

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

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

 

 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments