How to use Absolute URL to set Background Image in React In ReactJS

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.

Example

This example uses an environment variable to add the background image.

Javascript




// Filename - App.js
 
import React, { Component } from "react";
 
class App extends Component {
    render() {
        const myStyle = {
            backgroundImage: `url(${
                process.env.PUBLIC_URL + "/image.png"
            })`,
            height: "100vh",
            marginTop: "-70px",
            fontSize: "50px",
            backgroundSize: "cover",
            backgroundRepeat: "no-repeat",
        };
        return (
            <div style={myStyle}>
                <h1>w3wiki</h1>
            </div>
        );
    }
}
 
export default App;


Step to run the application: Open the terminal and type the following command.  

npm start

Output: Open the browser and our project is shown in the URL http://localhost:3000/

How to set background images in ReactJS

Background images can improve the UI and user experience of web apps by making the appearance better. These images can be some shape or shade using color gradients.

Many developers prefer using some sort of background image on their page, instead of the default plain white background. In this tutorial, we will look at different methods to add background images to your application in ReactJS.

Similar Reads

How to Set a React Background Image

There are many methods to apply a background image to your web application in React. We will be discussing 5 easy methods to add background images in ReactJS....

Using Inline CSS to set Background Image in React

In this method, we add the style attribute inside the element itself....

Using External CSS to set Background Image in React

...

Using Absolute URL to set Background Image in React

In this method, we add an external CSS file to set a background image for the React component....

Using Relative URL to set Background Image in React

...

Add background image from src/ folder in React

...

Wrapping Up

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....

Contact Us