'Image in public folder not loading after deployment
I am using React to create my personal portfolio website.
I store images in the public folder and use them as src='imageNames'.
However, After I deployed the website using gitpage, the images no longer work in local development, though they work in production. They show a broken images instead. Any ideas? Thanks!
To Reproduce,
1.Create a boilerplate app and deploy the app to gitpage following https://github.com/gitname/react-gh-pages
2.Replace <img src='{logo}' className="App-logo" alt="logo" /> with <img src='logo192.png' className="App-logo" alt="logo" />
e.g.
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<img src='{logo}' className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
Update: Importing images outside of the public folder work. I am wondering why public folder is not working anymore after deployment?
Solution 1:[1]
If you're using create-react-app it could be caused by the homepage value in your package.json being different than before you deployed:
{
"homepage": "http://yourUsername.github.io/yourProjectName"
}
If that's the case, this will change the default react directory to /yourProjectName.
So in your jsx you would need to add /yourProjectName by calling the following path instead:
<img src="./yourProjectName/imageName.png" />
More information about relative paths in the docs here.
Note: You could then create an environment variable and call that instead for better reusability.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Monstar |
