Correct image path in React.js
P粉024986150
P粉024986150 2023-08-21 14:24:49
0
2
623
<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>
P粉024986150
P粉024986150

reply all(2)
P粉509383150

In create-react-app, it seems that you cannot use relative paths to reference images. Instead, you can use import to bring in images:

import logo from './logo.png' // 图片的相对路径

class Nav extends Component { 
    render() { 
        return ( 
            <img src={logo} alt={"logo"}/> 
        )  
    }
}
P粉478188786

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" />

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template