I am trying to get my React App to render a background image in css. I need this because I want to use css queries to get different background image for different screen size. However, React is unable to get the background images.
.Background {
background-image: url("./blabla.jpeg");
height: 300px;
width: 600px;
}
export default function App() {
return (
<div className="App">
<div className="Background">Hello</div>
</div>
);
}
2
Answers
If you don’t want to use dynamic linking, you can store your images in
public
folder.The files in
src
folder do not get compiled unless they are imported, while files in public will be served as it is.If you are using CRA follow this documentation.
If you use Vite, follow this for dynamic linking or this for static serving of images.
Please add the assets to the specified path and update the path to ‘./assets/blabla.jpeg’. Also, ensure that you have imported the CSS file Correctly.