skip to Main Content

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.

Codesandbox link

.Background {
  background-image: url("./blabla.jpeg"); 
  height: 300px;
  width: 600px;
}

export default function App() {

  return (
    <div className="App">
      <div className="Background">Hello</div>
    </div>
  );
}

codesandbox css

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search