1

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.

codeouz
  • 53
  • 6

3 Answers3

1

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.

Hritik Sharma
  • 1,756
  • 7
  • 24
  • Thank you, very clear explanation. I'm planning on importing 10 to 15 images, would i have to write that import statment that many times or could i just do import baseball,basketbal,.... from 'folder' – codeouz Mar 23 '22 at 10:49
  • You must import all the images at the top as : import img1 from './img1.png' import img2 from './img2.png' so on and so forth. This link can help you with the importing all the images in one line https://stackoverflow.com/questions/42118296/dynamically-import-images-from-a-directory-using-webpack – Hritik Sharma Mar 23 '22 at 11:31
0

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"
0

Basically what you have to do is import that file where your image is stored and use it in the img tag.

import React from "react"
import logo from "./logo.png" // Tell webpack this JS file uses this image

function Header() {
  // Import result is the URL of your image
  return <img src={logo} alt="Logo" />
}
export default Header;
Manishyadav
  • 1,361
  • 1
  • 8
  • 26