How to set Application Background Image in React?

You may see many SPA (Single Page Architecture) applications having a background image. We can easily set the application’s background image in the App.js file of your React App. You may add the following styling to your parent div.

<div style={{ 
      backgroundImage: 'url('+wallpaper_url+')',
      backgroundRepeat: 'no-repeat',
      width:'100vw',
      height:'100vh',
      backgroundSize: 'cover',
      position: 'absolute'
}}>

This sets the image URL passed as your application’s background or wallpaper image, covering the entire screen. You can then add child components on this background.

Background with useState

You might have heard of the ‘useState‘ hook in React. It is used to for variables which may change state throughout the application’s processes. We can apply the ‘useState‘ hook to the background image, in cases we need to change the background of the application. Use the code below to define your wallpaper image using useState.

const [wallpaper, setWallpaper] = useState("/wallpapers/123.jpg");

You can now use the wallpaper variable above while rendering the wallpaper image. In functions where you change the wallpaper, use the setWallpaper function and pass the background image URL as a string, as shown below.

setWallpaper("/wallpapers/124.jpg");

You can change the wallpaper anytime and use the wallpaper variable, as shown below.

<div style={{ 
      backgroundImage: 'url('+wallpaper+')',
      // other same style
}}>

So, whenever your wallpaper state changes, it is reflected in the background image div style.

When working with state changes, always keep note that state changes between parent and child components require passing down the state variables to the child component to use them. You can find detailed example for this case here.

Leave a Comment