Home > Enterprise >  How to import images in react from different file?
How to import images in react from different file?

Time:03-23

first off here is an image of my project structure to help with visualising the issue here:

enter image description here

in my components folder there is a file homepage.js, im trying to import an image which is in the folder icons. im not to sure how to reference the image since the image and the homepage file are not in the same folder. I tried placing the image in the components file and importing it like this:

import baseball from './baseball.png';

It works as intended. Im trying to find out how to import the image while in the icon folder without having to move it.

CodePudding user response:

So, you would need to put the image in the public folder:

  1. If you want make a assets folder in the public folder

  2. Put the image in there

  3. The src is now

    src="assets/baseball.png"

or this, if you didn't make a folder in the public folder

src="baseball.png"

CodePudding user response:

Suppose you are in homepage.js inside components folder .

Then in order to access image inside Icons folder , you have to import the image as shown below .

import basebass from '../../Icons/baseball.png';

Let us divide each step and get a better clarity of the path .

../ going back to previous folder . so when we encounter ../ we are now in src folder and not in components folder .

The second time we encounter ../ from src folder , then we get redirected to firstv folder . As shown , Icons folder is inside firstv folder so we can directly go inside Icons folder by doing this , /Icons .

As , image is stored inside Icons folder then we can directly import it from there in our react file.

  • Related