Set background image in ReactJs

Anupam Srivastava
2 min readJan 16, 2021

--

In this section I am going to tell you how to set image as background in your react app. You can add background to your whole page as well as a desired element of the page i.e. any div or section.

  1. If you want to set an image as background for the entire page, you can follow the code given below:
    In index.css of your react app add this:

After this, add desired image to your page background using background css attribute in same index.css as shown in the following code. Remember that you need to put the image in the src folder. Here’s a snippet depicting the same.

image is stored in src folder
output: brick.jpg is set to background

Hurrah! Image is set to background for the entire screen now.

2. If you want to set an image as background to any element, you can use inline styling as given in the code below:
In your app.js, first import the image which you want as your element background. After that create your style object, here divStyle, ( include your background url and size ) and set that object to the inline style of desired element . Here’s a snippet illustrating that.

code

Image will be set to the background of the selected div as shown.

output: for the above code

Hope you found this blog helpful .

--

--