How to set background image in Reactjs using external css?

Viewed 1655

I have an app that I created using create-react-app and I want to set the background image of the header element. I tried using external CSS in Home.css and imported it from Home.js with this code:

header{
background-image: url(./images/bg-hero-mobile.svg);
}

The above approach is showing me this error:

./src/Home.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src??postcss!./src/Home.css) Error: Can't resolve '/images/bg-hero-mobile.svg' in 'C:\Users\User\Documents\own-authenticator\frontend\rca-authenticator-frontend\src'

Here is my file structure:

Folder structure

2 Answers

Error: Can't resolve '/images/bg-hero-mobile.svg' in 'C:\Users\User\Documents\own-authenticator\frontend\rca-authenticator-frontend\src'

it's a path issue. The webpack was not able the find the file on the given path i.e the file does not exist on the provided path.

To give the path as per the current app structure

header{
background-image: url(../public/images/bg-hero-mobile.svg);
}

Or you can simple put the images folder under src directory.

Since the new release of create-react-app v4.0.1 it is not acceptable to access images through a css file but you can access it from jsx and inline css. If you want to access a resource like images,fonts you have to put them in src folder. In this case I have to move images folder into src folder and use this code to access it:

header{
background-image: url(./images/bg-hero-mobile.svg);
}
Related