Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 862
vedran Avatar asked Dec 27 '16 13:12

vedran


People also ask

How do I add a background image in style React?

Method 5: Add background image from src/ folder If the image resides inside the src directory, the user can import it inside the component filer and set it as the background image. In this file, we will import the image and set it as a background image of the div element.

How do I import an image into React component?

To import and use an image in a React component:Import the local image, e.g. import MyImage from './thumbnail. webp'; . Pass the imported image to the src prop on the img element. For example, <img src={MyImage} alt="horse" /> .


1 Answers

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}); `; 
like image 189
Ilja Avatar answered Sep 18 '22 13:09

Ilja