What is the best way to replace image with default image on error in ReactJS ?
Last Updated :
05 Dec, 2023
In this article, we will learn to replace the image with the default image when an error occurs in ReactJS. Sometimes, it happens that the image source URL is broken or empty. In this scenario, we can replace the current image source URL with the default image source URL to fix the image rendering error.
Prerequisites:
Steps to Create the React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Project Structure:
Project Structure
The updated dependencies in package.jsopackage.json:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}
Example: The below example shows you that when the image URL is broken, it shows alternative text only. Add the below code to the respective files.
- App.js: In this file, we have implemented the code for the broken image URL, and it shows alternative text only.
Javascript
import React, { Component } from 'react' ;
class App extends Component {
render() {
return (
<div style={{ width: "600px" }}>
{ }
<div className= 'imageDiv' style={{
border: '3px dashed red' , margin: "10px" ,
}}>
<h2>Original Image</h2>
<img
src=
alt= "Original one"
/>
</div>
{ }
<div className= 'imageDiv' style={{
border: '3px dashed red' , margin: "10px" ,
}}>
<h2>When image URL is Broken</h2>
<img
src= ""
alt= "broken Image"
/>
</div>
</div>
);
}
}
export default App;
|
Steps to Run: To start the react app, run the below command on your terminal and verify that react app is working fine.
npm start
Output:
Output
To solve a broken image error, we can replace the image source URL with the default image URL:
Example:Â This example resolves the error of a broken image and replaces it with the default image. Add the below code to the respective files.
Javascript
import React, { Component } from 'react' ;
class App extends Component {
constructor(props) {
super (props);
this .state = {
defaultImage:
};
}
replaceImage = (error) => {
error.target.src = this .state.defaultImage;
}
render() {
return (
<div style={{ width: "600px" }}>
{ }
<div className= 'imageDiv' style={{
border: '3px dashed red' , margin: "10px" ,
}}>
<h2>Original Image</h2>
<img
src=
alt= "Original one"
onError={ this .replaceImage}
/>
</div>
{
}
<div className= 'imageDiv'
style={{
border: '3px dashed red' ,
margin: "10px" ,
}}>
<h2>When image URL is Broken</h2>
<img
src= ""
alt= "Opps! URL is broken"
onError={ this .replaceImage}
/>
</div>
</div>
);
}
}
export default App;
|
Steps to Run:Â To start the react app, run the below command on your terminal and verify that react app is working fine.
npm start
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...