4

Good evening.

I am facing an issue while using react in combination with styled components.

I have an image folder located in :

enter image description here

And I have my styled components in the following folder :

enter image description here

Inside the styled components I'm trying to import the image like this :

const FormImage = styled.div`
    width: 150px;
    height: 150px;
    margin: 0 auto;
    margin-top: -20%;
    background-image: url(../../img/testlogo.png);
`;

Im sure this is the right path. But somehow the image is not showing in the browser.

This is what i'm seeing in my browser :

enter image description here

Kevin.a
  • 4,094
  • 8
  • 46
  • 82
  • Possible duplicate https://stackoverflow.com/questions/41346413/importing-images-in-react-js-with-styled-components – Andy Hoffman Dec 03 '19 at 19:30

1 Answers1

10

Such path is not available in runtime (as CSS-in-JS like styled-component creates the CSS in runtime, although there are solutions with no-runtime), you should try one of the next approaches:

import ImgSrc from '../../img/testlogo.png';
const FormImage = styled.div`
    background-image: url(${ImgSrc});
`;

// or
const FormImage = styled.div`
    background-image: url(${require(`../../img/testlogo.png`)});
`;
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118