Search code examples
cssreactjsstyled-components

background image in styled components react


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


Solution

  • 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`)});
    `;