Setting background image in React with Inline Css

import React from "react";

function App() {
 return (
  <div style={{" ??? "}}
   This Is MY World!
  </div>
);
}

export default App;

There are four ways to set a backgroundImage style property using React’s inline CSS.

This blog will show you all four methods.


1. How to Set a Background Image in React Using an External URL.

function App() {
  return (
    <div style={{ 
      backgroundImage: `url("https://via.placeholder.com/500")` 
    }}>
      This Is MY World!
    </div>
  );
}

The code above will render one single <div>. With style property backgroungImage.

If the image is located somewhere online, You can set the background image by placing a URL() as mentioned above;


2. How to Set a Background Image in React From Your /src Folder

import React from "react";
import background from "./img/placeholder.png";

function App() {
  return (
    <div style={{ backgroundImage: `url(${background})` }}>
      This Is My World!
    </div>
  );
}

export default App;

If you bootstrap your application using Create React App and have your image inside the src/ folder, you can import the image first and then place it as the background of your element:

We set the background image using template string. so even if you have not added the image. It won’t show you a broken screen.


3. You can also include the absolute URL by using Create React App’s PUBLIC_URL environment variable.

<div style={{ 
  backgroundImage: `url(${process.env.PUBLIC_URL + '/image.png'})` 
}}>
 This Is My World!
</div>

When you run it locally, it will look like a relative URL instead of absolute URL:

React scripts will handle the value of the PUBLIC_URL value.

The absolute URL will be seen when you deploy React into production application.


4. How to Set a Background Image in React Using the Relative URL Method.

<div style={{ backgroundImage: "url(/image.png)" }}>
  This Is My World!
</div>
  • The public/ folder in Create React App can be used to add static images
  • You can access it thought <your host an address>/images.png.
  • When running React in your computer, it should be at http://localhost:3000/image.png.
  • Once you set the path the browser will look for an image <host address>/image.png.
  • If you want to keep this organised you can create a folder called images/ or inside of you public/ folder
  • My-App(name of the folder you created)>public>images.

5. How to Set a Background Image with Additional Properties.

<div style={{ 
  backgroundImage: `url(${process.env.PUBLIC_URL + '/image.png'})`,
  backgroundRepeat: 'no-repeat',
  width:'350px' 
}}>
  This Is My World!
</div>

The properties set above will add background-repeat: no-repeat and width: 350px with the background-image style to the <div> element.

Thank you for reading, and I hope you found this article useful.