1

I have a react app with this project structure:

enter image description here

In my Home component and About component I have two images With src set to : <img src="/img/charlie1.jpg" alt="charlie home pic" /> and <img src="/img/charlie2.jpg" alt="charlie about pic" />

So I assume it will start looking in the root folder then the image folder then find the pictures in there.

This works fine when I’m developing on my local machine The images will display correctly.

But when I build it and move the files to prod the images won’t work It looks for the image at this path: https://xyz.github.io/img/charlie2.jpg instead of https://xyz.github.io/charlieReact/img/charlie2.jpg

How can I fix this problem?

If I change the image src to : <img src="./img/charlie1.jpg" alt="charlie home pic" />

Then it works in github pages, but then the images won’t display when I’m on my local machine…

psj01
  • 3,075
  • 6
  • 32
  • 63
  • May I ask why you don't want to import the images in the JavaScript, i.e. `import charlie1 from './charlie1.jpg'`? Do you have too many images? Maybe [this](https://stackoverflow.com/questions/37644265/correct-path-for-img-on-react-js#answer-49170502) could work. – Tholle Nov 09 '18 at 22:01
  • Ah! that worked. Is that how it should be done? – psj01 Nov 09 '18 at 22:08
  • 1
    It's a good idea to import the images into the JavaScript and use the imported variable whenever you can, and the URLs will just work by themselves. If your page has a root other than `/` and you have assets in the `public` directory, [you most likely have to do some extra logic in the code](https://github.com/facebook/create-react-app/issues/2854#issuecomment-317911513). – Tholle Nov 09 '18 at 22:12

1 Answers1

1

It's a good idea to import the images into the JavaScript and use the imported variable whenever you can, and the URLs will just work by themselves.

import charlie1 from './charlie1.jpg';

<img src={charlie1} />

If your page has a root other than / and you have assets in the public directory, you most likely have to do some extra logic in the code.

package.json

{
  "homepage": "https://xyz.github.io/charlieReact"
}

App.js

<img src={`${process.env.PUBLIC_URL}/img/charlie1.jpg`} />
Tholle
  • 108,070
  • 19
  • 198
  • 189