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