0

In React: I couldn't get a background image to load from my CSS file. Upon researching it, I learned that I should have my images folder in my src folder and not my public folder. So I moved my images folder. My background image from my CSS file now works, but React isn't finding any of my other images, which is was before.

I have code such as:

setImage(`./images/${temp.img_bg}`);

and

<img src="/images/logo.png" alt="Logo" />

I've tried different things with the path, but to no avail.

John G.
  • 29
  • 4

1 Answers1

0

The problem probably because the path is not good i'd like to recommend you this way of importing images.

import tmpImage from "./exmpleImage.png";

and then you use the img like this

<img src={tmpImage} alt="Logo">

Another recommended tip is to put all you're images in a specific hierarchy something like

src -> assets -> images

and most of the times you should import the images like this

import tmpImage from "../../assets/images/exmpleImage.png";

every "../" will get you one folder backward in the path.

Micahel Hamami
  • 179
  • 1
  • 10
  • Well, partial success. I created an assets folder and moved my images folder into it. I have a couple images hardcoded in my component, and the import method worked for those. But all the other images come from a JSON file and have the same name (team.img). I'm mapping through an array of objects, and the output is: `
    {team.nickname}` . These images don't appear.
    – John G. Sep 15 '21 at 13:11
  • i think i understand what you need , look at the answer here: https://stackoverflow.com/questions/54024112/how-to-import-images-from-json-data-into-create-react-app if this works for you tell me and ill update my answer aswell – Micahel Hamami Sep 15 '21 at 14:33
  • No, no luck. First, my JSON file is 7500 lines, so I'm not changing that. Many hundreds of lines are for images. But I did try adding the path to a couple, and no luck there. Can't use the require method in JSON if it's not inside quote marks. Does it matter where the JSON file is? Mine is in the public folder. This is my first React app, so I'm learning a lot. Thanks. – John G. Sep 15 '21 at 16:24
  • I was studying that link you gave me, googled something else about the require method, and I found something that worked. First I moved my images folder into my components folder. Then I used: `{team.nickname}`. Things started working when I added the dot default. Thanks again for your help. – John G. Sep 15 '21 at 22:16