Home  >  Q&A  >  body text

Correct image path in React.js

<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粉024986150P粉024986150396 days ago551

reply all(2)I'll reply

  • P粉509383150

    P粉5093831502023-08-22 00:48:37

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

    reply
    0
  • P粉478188786

    P粉4781887862023-08-22 00:46:47

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

    reply
    0
  • Cancelreply