How to set background images in ReactJS ?
Sometimes, users need to set background images while developing the react app. In this article, we are going to discuss all methods to set background images in react app.
We will discuss how to set the background image using inline CSS and external CSS. We will also discuss several methods to add the URL of the background image.
Prerequisites: The pre-requisites for this project are:
Creating react application
Step 1: The user can create a new react project using the below command.
npx create-react-app testapp
Step 2: Next, the user needs to move to the test app project folder from the terminal using the below command.
Project structure: It looks like the below image.
Method 1: Using inline CSS: In this method, we add the style attribute inside the element itself.
In App.js, We will add a style attribute inside the div element and set the background image for a div element using inline CSS.
Method 2: Using external CSS: In this method, we add an external CSS file to set a background image for the react component.
In App.js, we will add a simple div element with the className attribute. Also, we import an external CSS file to set a background image for the div element.
In App.css, we will add a code style react component added inside the App.js file. We will access the div element from the App.js file using the className attribute and set the background image.
Method 3: Using Absolute URL: Users can access the background image directly from the public/ folder via absolute URL using the environment variable. Before using this method, Don’t forget to add an image inside the public folder otherwise it will show you a compilation error.
Here, we will add code to set background images using inline CSS and environment variables.
Method 4: Using Relative URL: Users can access images from the public/ folder or any child folder of the public folder via relative path URL. The URL to access the image should be like <host_name>/image.png.
In this file, we set a background image for the div element using the relative path of the image.
Method 5: Add background image from src/ folder If the image resides inside the src directory, the user can import it inside the component filer and set it as the background image.
In this file, we will import the image and set it as a background image of the div element.
Steps to run react application: You can run the react application using the below command.