How to set a Background Image With React Inline Styles ?
Last Updated :
01 Oct, 2024
Setting a background image with React inline style is a straightforward method of using the images as background to enhance the UI of the wen application.
How to Set Background Image in React ?
To set background image with react inline styles we will be using the style attribute. This style attribute is used to add inline CSS to the individual element. We will use the Image in multiple ways to set the background image.
Steps to Create React Application
Step 1: Create a React application using the following command:
npx create-react-app myapp
Step 2: After creating your project folder i.e. myapp, move to it using the following command:
cd myapp
Project Structure:

List of dependencies in the package.json file are:
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
Approach 1: Set background image using external URL
If the image located somewhere online, then the background image of the element can be set like this:
JavaScript
// Filename: App.js
import React from "react";
const App = () => {
return (
<div
style={{
backgroundImage:
'url("https://media.geeksforgeeks.org/' +
'wp-content/uploads/20201221222410/download3.png")',
height: "300px",
backgroundRepeat: "no-repeat"
}}
>
<h1> HELLO </h1>
</div>
);
};
export default App;
Approach 2: Set background image using the Absolute URL method
If you put your image, for example, background.jpg file inside the public/ folder, you can include the absolute URL by using the PUBLIC_URL environment variable.
JavaScript
// Filename: App.js
import React from "react";
const App = () => {
return (
<div
style={{
backgroundImage: `url(${
process.env.PUBLIC_URL + "/background.jpg"
})`,
height: "300px",
backgroundRepeat: "no-repeat"
}}
>
<h1>Hello</h1>
</div>
);
};
export default App;
Approach 3: Set background image using the Relative URL method
If you put your image, for example, background.jpg file inside the public/ folder in the react app, you can access it at <your host address>/background.jpg.
You can then assign the URL relative to your host address to set the background image like this:
JavaScript
// Filename: App.js
import React from "react";
const App = () => {
return (
<div
style={{
backgroundImage: "url(/background.jpg)",
height: "300px",
backgroundRepeat: "no-repeat"
}}
>
<h1>Hello</h1>
</div>
);
};
export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: