onedkr onedkr - 1 month ago 20
Javascript Question

Correct path for img on React.js

I have some problem with my images on my react project. Indeed I always thought that relative path into src attribute was built on the files architecture

Here my files architecture:

components
file1.jsx
file2.jsx
file3.jsx
conainter
img
js
...


However I realized that the path was build on the url. In one of my component (for example into file1.jsx) I have this :

localhost/details/2
<img src="../img/myImage.png" /> -> Works

localhost/details/2/id
<img src="../img/myImage.png" /> -> doesn't works, images are not displayed


How is it possible to solve this problem ? I want that in any form of routes handled by react-router, all images can be displayed with the same path.

Answer

You're using a relative url, which is relative to the current url, not the file system. You could resolve this by using absolute urls

<img src ="http://localhost:3000/details/img/myImage.png" />

But that's not great for when you deploy to www.my-domain.bike, or whatever. Better would be to use a url relative to the root directory of the site

<img src="/details/img/myImage.png />