Search code examples
reactjsstyled-components

React.js styled-components importing images and using them as div background


I am using styled-components and am trying to set a background image like so

const HeaderImage= styled.div`
    background-image: url('../../assets/image.png');
';

I've also tried without the quotes, like so

const HeaderImage= styled.div`
        background-image: url(../../assets/image.png);
 ';

In both cases, I get the same result

http://localhost:3000/assets/image.png Failed to load resource: the server responded with a status of 404 (Not Found)

I am using Richard Kall's react starter

The file is definitely in the specified location.

Am I loading it incorrectly?

I should mention, I'm very new to this (React, and styled-components)


Solution

  • You should import images in the following manner (assuming that you have webpack configured for importing media assets).

    import myImage from '../../assets/image.png';
    
    /* ... */
    
    const HeaderImage = styled.div`
      background-image: url(${myImage});
    `;