Correct image path in React.js
P粉024986150
2023-08-21 14:24:49
<p>I'm having some issues with images in my React project. In fact, I always thought that the relative path in the src attribute was constructed based on the file's schema. </p>
<p>This is my file structure: </p>
<pre class="brush:php;toolbar:false;">components
file1.jsx
file2.jsx
file3.jsx
container
img
js
...</pre>
<p>However, I realized that the path is built based on the URL. In one of my components (e.g. file1.jsx) I have the following code: </p>
<pre class="brush:php;toolbar:false;">localhost/details/2
<img src="../img/myImage.png" /> -> works normally
localhost/details/2/id
<img src="../img/myImage.png" /> -> not working, the image cannot be displayed</pre>
<p>How to solve this problem? I want all pictures to be displayed with the same path in any routing form handled by react-router. </p>
In
create-react-app
, it seems that you cannot use relative paths to reference images. Instead, you can use import to bring in images:You are using a relative URL, which is relative to the current URL rather than the file system. You can solve this problem by using absolute URL
<img src ="http://localhost:3000/details/img/myImage.png" />
However, this is not ideal when you deploy to www.my-domain.bike or any other site. A better approach is to use a URL relative to the site root
<img src="/details/img/myImage.png" />