Home > Web Front-end > JS Tutorial > body text

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

Linda Hamilton
Release: 2024-10-26 12:36:29
Original
260 people have browsed it

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 
... 
Copy after login

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 -->
Copy after login

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;}/> 
        )  
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!