Correct path for img on React.js

onedkr picture onedkr · Jun 5, 2016 · Viewed 329.7k times · Source

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
container
img
js 
... 

However I realized that the path is built 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 work, 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

claireablani picture claireablani · Oct 9, 2016

In create-react-app relative paths for images don't seem to work. Instead, you can import an image:

import logo from './logo.png' // relative path to image 

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