React Background Image Tutorial – How to set backgroundImage with Inline CSS Style
There are four ways to set a
backgroundImage style property using React’s inline CSS.
This tutorial will show you all four methods, with code samples for each.
How to Set a Background Image in React Using an External URL
If your image is located somewhere online, you can set the background image of your element by placing the URL like this:
The code above will render a single
<div> element with the style
background-image: url(https://via.placeholder.com/500) applied into it.
How to Set a Background Image in React From Your /src Folder
If you bootstrap your application using Create React App and have your image inside the
src/ folder, you can
import the image first and then place it as the background of your element:
When you run the
npm start command, React will show a “Failed to Compile” error and stop the build when the image is not found:
This way, you won’t show any broken image links on your web app. In the code above, the value of
How to Set a Background Image in React Using the Relative URL Method
public/ folder in Create React App can be used to add static assets into your React application. Any files you put inside the folder will be accessible online.
If you put an
image.png file inside the
public/ folder, you can access it at
<your host address>/image.png. When running React in your local computer, the image should be at
You can then assign the URL relative to your host address to set the background image. Here’s an example:
By setting the URL path to
/image.png like the example above, the browser will look for the background image at
<your host address>/image.png.
You can also create another folder inside
public/ if you want to organize your images into folders. For example:
Don’t forget to adjust the
backgroundImage value to
url(/img/image.png) if you decide to create the folder.
How to Set a Background Image in React Using the Absolute URL Method
You can also include the absolute URL by using Create React App’s
PUBLIC_URL environment variable like this:
When you run this on your local computer, React scripts will handle the value of the
PUBLIC_URL value. When you run it locally, it will look like a relative URL instead of absolute URL:
The absolute URL will only be seen when you deploy React into production application later.
How to Set a Background Image with Additional Properties
If you want to customize the background image further, you can do so by adding additional properties after the
backgroundImage. Here’s an example:
The properties set above will add
background-repeat: no-repeat and
width: 250px together with the
background-image style to the
Thank you for reading, and I hope you found this article useful. If you have any questions, you can find me on Twitter. I will share some short developer tips from time to time as well. 🙂
Read More …