Home  >  Article  >  Web Front-end  >  How to Resolve Image Path Issues with React Router in React.js?

How to Resolve Image Path Issues with React Router in React.js?

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 12:36:29261browse

How to Resolve Image Path Issues with React Router in React.js?

Img Path Resolution in React.js

In React.js, the src attribute of the element is expected to contain the URL of the image. However, it appears that in some cases, relative paths are not being resolved correctly, especially in the context of React Router.

Consider the following file structure:

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

In file1.jsx, the following code is used to display an image:

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

localhost/details/2/id
<img src="../img/myImage.png" /> <!-- doesn't work -->

As you observed, the relative path works in the first case but not in the second case. This is because the relative path is resolved based on the URL, not the file architecture.

To ensure that images are displayed correctly regardless of the route, one solution is to import the images using the following syntax:

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

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

By importing the image, you are ensuring that it is a bundled resource and will be available in all components, regardless of the current route.

The above is the detailed content of How to Resolve Image Path Issues with React Router in React.js?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn