How to use Relative URL to set Background Image in React In ReactJS
Users can access images from the public/ folder or any child folder of the public folder via a relative path URL. The URL to access the image should be like <host_name>/image.png.
Example
This example uses the relative path of the image to set the required image as the background.
Javascript
// Filename - App.js import React, { Component } from "react" ; class App extends Component { render() { const myStyle = { backgroundImage: "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