Home >Web Front-end >JS Tutorial >Why Can\'t I Load Local Images in My React App?
Background:
Local images sometimes fail to load in React apps, despite external images rendering successfully. This can be a frustrating issue, especially for developers who rely on local images for design and functionality.
Troubleshooting:
The problem often lies in the way images are sourced in the React application. Here's why:
Solution:
To resolve this issue, use the require() function to import local images. Here's an example:
import React, { Component } from 'react'; class App extends Component { render() { return ( <div className="home-container"> <div className="home-content"> <div className="home-text"> <h1>foo</h1> </div> <div className="home-arrow"> <p className="arrow-text"> Vzdělání </p> <img src={require('/images/resto.png')} /> </div> </div> </div> ); } } export default App;
By using require('/images/resto.png'), you're instructing Webpack to process the image and replace the source path accordingly. This ensures that the image is properly loaded and displayed in the application.
The above is the detailed content of Why Can't I Load Local Images in My React App?. For more information, please follow other related articles on the PHP Chinese website!