Home > front end >  React importing image does not work for CSS
React importing image does not work for CSS

Time:11-03

I am having problems importing my image for CSS. I have imported the image as a test and it works when using it in the img tag using src={furnitureBG}.

I followed the docs and imported the image and then using the path as the value for url(''). However, no image renders and there is no error message.

I know the path is correct because when I use the code

<img src={furnitureBG} />

the image I desire renders. I am just wondering why this is not working on the following code for CSS background.

import furnitureBG from '../images/furniture-bg-7.png';

const Container = styled.div`
    height: 100vh;
    width: 100vw;
    background: linear-gradient(rgba(0,0,0,.35), rgba(0,0,0,.35)), url('../images/furniture-bg-7.png');
`

CodePudding user response:

You can use url(${furnitureBG?.src}) in order to render image using styled component.

   import furnitureBG from '../images/furniture-bg-7.png';

   const Container = styled.div`
      height: 100vh;
      width: 100vw;
      background: linear-gradient(rgba(0,0,0,.35), rgba(0,0,0,.35)), url(${furnitureBG?.src});
   `

CodePudding user response:

You can move the /images folder into the public folder:

App.js

const Container = styled.img`
  background-image: url("/images/asdf.png");
  width: 100vw;
  height: 100vh;
`;

function App() {
  return (
    <div className="App">
      <Container />
    </div>
  );
}

Directory structure:

 - project
   - public
     - images
       - asdf.png
   - src
     - App.js
  • Related