Saturday, August 30, 2025
HomeLanguagesJavascriptHow to set a background Image With React Inline Styles ?

How to set a background Image With React Inline Styles ?

A React project is created using create-react-app command and the task is to set a background image using react inline styles. There are three approaches that are discussed below:

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:

Filename: App.js

Javascript




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.

Filename: App.js

Javascript




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:

Filename: App.js

Javascript




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: 

RELATED ARTICLES

Most Popular

Dominic
32249 POSTS0 COMMENTS
Milvus
80 POSTS0 COMMENTS
Nango Kala
6617 POSTS0 COMMENTS
Nicole Veronica
11792 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11838 POSTS0 COMMENTS
Shaida Kate Naidoo
6731 POSTS0 COMMENTS
Ted Musemwa
7012 POSTS0 COMMENTS
Thapelo Manthata
6689 POSTS0 COMMENTS
Umr Jansen
6701 POSTS0 COMMENTS