Add background image from src/ folder in React
If the image resides inside the src directory, the user can import it inside the component filer and set it as the background image.
Example
This example imports the image from the project src directory and sets it as a background image of the div element.
Javascript
// Filename - App.js import React, { Component } from "react" ; import background from "./image.png" ; class App extends Component { render() { const myStyle = { backgroundImage: `url(${background})`, 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.