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

vedran picture vedran · Dec 27, 2016 · Viewed 40.6k times · Source

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)

Answer

Ilja picture Ilja · Jan 2, 2017

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