Open In App

What is the best way to replace image with default image on error in ReactJS ?

Last Updated : 05 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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" }}>
 
                {/* original image div */}
                <div className='imageDiv' style={{
                    border: '3px dashed red', margin: "10px",
                }}>
                    <h2>Original Image</h2>
                    <img
                        src=
                        alt="Original one"
                    />
                </div>
 
                {/* broken image 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:
        };
    }
 
    // replace image function
    replaceImage = (error) => {
        //replacement of broken Image
        error.target.src = this.state.defaultImage;
    }
 
    render() {
        return (
            <div style={{ width: "600px" }}>
 
                {/* original image */}
                <div className='imageDiv' style={{
                    border: '3px dashed red', margin: "10px",
                }}>
                    <h2>Original Image</h2>
                    <img
                        src=
                        alt="Original one"
                        onError={this.replaceImage}
                    />
                </div>
 
                {/* replacing broken image by calling
                the replaceImage() function on error
        */}
                <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:



Similar Reads

Difference between One-way Binding and Two-way Binding
In this article, we will learn the concept of data binding in Angular. We will also explore its types &amp; examine the differences between one-way binding and two-way binding in angular. Data binding is a way to synchronise the data between the model and view components automatically. AngularJS implements data-binding that treats the model as the
3 min read
What is the difference between one-way data flow and two-way data binding in vue.js?
Vue.js is an open-source front-end JavaScript framework for building user interfaces and single-page applications. It follows Model-View-ViewModel (MVVM) architecture pattern. Vue.js has many in-built directives for DOM manipulation such as v-bind, v-on, v-model, etc. In this article, we will learn about the one-way data binding &amp; two-way data
7 min read
How to replace dropdown-toggle icon with another default icon in Bootstrap ?
Bootstrap provides the option of adding a dropdown to our websites. The default icon on the dropdown button is the 'downward solid arrow' logo. Even though it serves its purpose, most of the modern-day websites nowadays use Bootstrap. Therefore, the icon might look very generic to the visitor.Program: C/C++ Code &amp;lt;!DOCTYPE html&amp;gt; &amp;l
3 min read
JavaScript/TypeScript: Standard way to keep the cause of an Error
In this article, we will try to understand that what's the standard way to keep the cause of an Error in JavaScript (or in TypeScript) with the help of certain coding examples. Since there is no such provision provided in JavaScript/TypeScript where directly we may be able to find out the cause of an error (like no such property or in-built method
2 min read
How to set default value in select using ReactJS ?
Dropdown and select elements are frequently used in forms where you want to set a default value in select using React Js. In HTML, the 'selected' attribute in the option tag is used to set the default value in the select menu. The same approach can also be used with React to set a default value if we are not using React Select Component. However, i
3 min read
Redux Toolkit Better way to write Redux code in ReactJS
Redux Toolkit is used for writing redux code but in a more concise way. Redux Toolkit (RTK) solves three bigger problems that most of the developer's face who used redux in a react application. Too much code to configure the store.Writing too much boilerplate code to dispatch actions and store the data in the reducer.Extra packages like Redux-Thunk
4 min read
How to retrieve error message using Exception class in PHP when error occurred ?
Exception handling is the important part of PHP in which we deal with how to maintain the flow of the program if there is an error or exception that occurs during the compilation. As you know we can handle the exception by throw, try-catch, die method so now we understand how to retrieve the error message using exception class by given below exampl
2 min read
Difference between throw Error('msg') and throw new Error('msg')
The throw statement allows you to create an exception or a custom error. The exception can be like a Javascript string, a number, a boolean, or an object. So, If you use this statement together with the try...catch statement. It allows you to control the flow of the program and generate accurate error messages. For example: throw "too small" (throw
3 min read
Express Returns Servers HTML Error Page Instead of res.json Error Message
ExpressJS is a backend web application framework built on top of NodeJS which helps us manage the server and routing. It has some powerful functionalities like middleware, templates, and debugging which help us to write efficient and faster code. It helps us extensively in building web applications. In this article, we will see why "Express returns
3 min read
Difference between Type Error and Reference Error in JavaScript
JavaScript is one of the most popular programming languages in the world, and it is used by millions of developers to create dynamic and interactive web applications. However, like any programming language, JavaScript is not without its quirks and pitfalls. Two common issues that developers often encounter when working with JavaScript are Type Erro
6 min read