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: