How to Set Background Image in React JS

In this tutorial, you will learn how to set or add background image in react js apps using external, internal, src, absolute url, and additional properties.

Here are five ways to set a background image in React apps:

1 – Set a Background Image in React Using an External URL

If your image is located on some platform or any other server; So you can set the background image of your element by placing the URL like this:

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

2 – Set a Background Image in React From Your /src Folder

To import the image from the src folder and place it as the background of your element:

import React from "react";
import background from "./img/placeholder.png";
function App() {
return (
<div style={{ backgroundImage: `url(${background})` }}>
Hello World
</div>
);
}
export default App;

3- Set a Background Image in React Using the Relative URL Method

If you put an image.png file inside the public/ folder, you can access it at <your host address>/image.png. When running React in your local computer, the image should be at http://localhost:3000/image.png.

You can then assign the URL relative to your host address to set the background image. Here’s an example:

<div style={{ backgroundImage: "url(/image.png)" }}>
Hello World
</div>

4 – Set a Background Image in React Using the Absolute URL Method

To use the absolute URL of image to use PUBLIC_URL environment variable for setting image like this:

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

5 – Set a Background Image with Additional Properties

To customize the background image further, you can do so by adding additional properties after the backgroundImage. Here’s an example:

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

Conclusion

In this tutorial, you have learned 5 ways to set background image in react js apps.

Recommended React JS Posts

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *