How to set a background image from the public folder in React

Last updated on Sep 26, 2020 by Suraj Sharma



In this tutorial, you will learn how you can import an image from a public folder and set the image as a background image of a react element.

It is not recommended to keep images and other static files in the public folder because webpack does not minify the files present in the public folder, resulting in a large bundle size and poor web performance.

This tutorial is especially targeted for projects created using create-react-app CLI.



Getting Started


create-react-app cli stores /public folder url as an environment variable ‘PUBLIC_URL’, which is accessible across the JSX files inside the /src folder.



A trivial example of using images/files from the public folder on a jsx file


<img src={`${process.env.PUBLIC_URL}/images/logo.png`} />


How to set a background-image property of an inline style?


This example demonstrates how you can set a background image to a react element using the element's style props


<div
  style={{
    width:480,
    height:480, 
    background: `url('${process.env.PUBLIC_URL}/logo512.png')`
  }}
>
</div>


How to reference a public folder image from a css file inside the /src folder?


The public folder can be accessed on a css file by adding a leading forward slash '/' on the background image url


.bg-image {
  background-image: url('/images/logo512.png');
  width: 480px;
  height: 480px
}

<div className="bg-image">
      
</div>


Conclusion


In this tutorial, you have learnt different ways to set a background image of an element in React. I think this article pretty much clears why you should not keep your static files inside the public folder.

I would also recommend to keep your css files and image files inside a src folder so it is easier to import them on react components, later when you build your project using npm run build, webpack will minify the files making your application run faster.



Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.