DEV Community

Utsav Akash Naskar
Utsav Akash Naskar

Posted on

How import images from one folder to another folder in React JS?

I have two folders/ directories within the src directory/ folder named images and components. Within components folder I have CustomerProfile.js and CustomerProfile.css and within images I have images.

Now I am using background: url('./images/customer-profile-bg.jpg'); in the css file to set up the background image but it's showing an error during compilation -

./src/components/CustomerProfile.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src??postcss!./src/components/CustomerProfile.css)
Error: Can't resolve './images/customer-profile-bg.jpg' in 'H:\GitTest\FINAL-YEAR-PROJECT-2021\front-end\src\components'

How to solve this error?

Top comments (4)

Collapse
 
valeriavg profile image
Valeria

TL;DR Use two dots in the beginning of the path instead of one, like this: background: url('../images/customer-profile-bg.jpg');

Path ./images/customer-profile-bg.jpg, being imported from src/components, is resolved to ./src/components/images/customer-profile-bg.jpg.

Path ../images/customer-profile-bg.jpg, on the other hand, will go one folder up from src/components and enter images folder. Which will be resolved to ./src/images/customer-profile-bg.jpg.

Collapse
 
utsav1999 profile image
Utsav Akash Naskar • Edited

Thank you for your explanation.

Collapse
 
stevenjburrows profile image
Steven Burrows

would it path not need to be '../images/customer-profile-bg.jpg'
As you need to come out of components directory before going into the images directory?

Collapse
 
kaiogomesx profile image
Kaio Gomes • Edited

import myImage from './images/customer-profile-bg.jpg'

<img src={myImage}></img>