Sandeep Amarnath
Sandeep Amarnath

Reputation: 6917

React doesn't display images placed in public folder when deployed to gh-pages but works in local host, why?

I built a simple app that renders three Cards that contain images in react's public folder. It works in localhost:3000 but when I'm seeking to deploy it to GitHub, gh-pages the images break. It seems it doesn't take the images from the public folder.

Steps I followed to deploy to gh-pages:

  1. created a key, value pair for homepage in package.json and added these two lines in the scripts section

    "predeploy":"npm run build", "deploy":"gh-pages -d build",

  2. npm install gh-pages --save-dev

  3. Committed and pushed all the above changes

  4. npm run deploy

These 4 steps successfully deployed my application

https://sandeep194920.github.io/CompoundComponents/ but, as you can see, the images don't show up which works in the localhost.

Let me know what is the mistake I am making here. Thank you.

Upvotes: 4

Views: 1967

Answers (1)

Ashok
Ashok

Reputation: 3591

The generated HTML will link to the image like this

<p><img alt="" src="/img/image.png" /></p>

But the image will actually be here.

So the issue can be avoided by using the relative paths and it's worth if maybe the repository name should automatically be added before the image URL if it's an absolute path.

Can try the below methods:

![](./img/image.svg)

![](img/image.svg)

<img src="./img/image.svg" />

<img src="img/image.svg" />

I tried it and worked for me check it here

Upvotes: 2

Related Questions