Horje
How To Check And Resolve Broken Images In React JS?

In web applications, handling images is crucial for a better user experience. Sometimes, images can fail to load due to various reasons like wrong URLs, server errors, network issues or browser caching issues. The better approach for handling an image error enhances the robustness of the application. In this article, we’ll explore how to check and manage broken images.

Prerequisites

These are the following approaches:

What are broken images?

The broken images come up whenever an HTML ‘<img>’ element is attempting to load an unavailable or invalid source. This shows a broken image icon, which offers a bad user experience and the application fails to deliver good quality.

Folder Structure:

Folder_Structure

Folder Strcutre

Dependencies:

 "dependencies": { 
"prop-types": "^15.8.1",
"react": "^18.2.0",
"react-dom": "^18.2.0" },
"devDependencies": {
"@types/react": "^18.2.66",
"@types/react-dom": "^18.2.22",
"@vitejs/plugin-react": "^4.2.1",
"eslint": "^8.57.0",
"eslint-plugin-react": "^7.34.1",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.6",
"vite": "^5.2.0" }

Steps to handle broken images

Step 1: Install Node.js

Before creating an application ensure the Node.js is installed on your system

Step 2: Create a new React application

  • We can create an application using Vite and create react app. We will see how to create react application using Vite.
  • Run the below command to create a new React application using Vite
npm create vite@latest react-broken-image -- --template react

Step 3: Redirect to project directory

Change you working directory by entering project name in the below command

cd react-broken-image

Step 4: npm install

Run the below command to install required dependencies

npm install

Using On-Error Event Handler

Create an ‘ImageWithDefault’ component for the ‘app’ component. Use the ‘onError’ event handler on the ‘<img>’ element to switch to a default image when loading fails. Steps include setting up state and the ‘useEffect’ hook for managing image URLs and error handling. Pass ‘src’, ‘defaultSrc’, and ‘altInfo’ as props from the parent component to ‘ImageWithDefault’, which features a ‘handleError’ method for image source updates on load failure.

Example: To demonstrate checking and resolving broken image in RectJS uisng the on-error event handler.

JavaScript
// ImageWithDefault.jsx

import { useState } from 'react';

const ImageWithDefault = ({ src, defaultSrc, altInfo }) => {
    const [imageSrc, setImageSrc] = useState(src);

    const handleError = () => {
        setImageSrc(defaultSrc);
    };

    return (
        <img
            style={{ maxWidth: '200px' }}
            src={imageSrc}
            onError={handleError}
            alt={altInfo}>
        </img>
    )
}

export default ImageWithDefault
JavaScript
// app.jsx

import './App.css'
import ImageWithDefault from './components/ImageWithDefault';

const App = () => {
    return (
        <>
            <ImageWithDefault
                src='src/assets/dummy-member.jpg'
                defaultSrc='src/assets/dummy-image-square.webp'
                altInfo="Test image for error handling"
            />
        </>
    )
}

export default App

We pass ‘src’ and ‘defaultSrc’ from the parent ‘app’ component to the child ‘ImageWithDefault’ component. The ‘src’ prop is stored in the ‘imageSrc’ state. An ‘onError’ function triggers on error, using the ‘setImageSrc’ setter to switch to ‘defaultSrc’ if the primary ‘src’ fails.

Using Higher-Order Component (HOC)

Create a ‘ImageWithError’ higher-order component (HOC) for use in the ‘app’ component. This HOC adds error handling capabilities to components that output ‘<img>’ elements, making it ideal for large-scale applications with numerous image-rendering components. Steps involve creating the HOC to wrap image-rendering components, providing straightforward ‘onError’ handling to manage broken images.

Example: To demonstrate checking and resolving broken image in RectJS uisng the Higher-Order Component.

JavaScript
// ImageWithError.jsx

import { useState } from "react";

const ImageWithError = (Component, fallbackSrc) => {
    return (props) => {
        const [error, setError] = useState(false);

        const handleError = () => {
            setError(true);
        };

        const src = error ? fallbackSrc : props.src;

        return <Component {...props} src={src} onError={handleError} />;
    };

};

export default ImageWithError;
JavaScript
// app.jsx

import "./App.css";
import ImageWithError from "./components/ImageWithError";

const ImageWithFallback = ImageWithError(
    ({ src, alt, ...props }) => <img src={src} alt={alt} 
     {...props} style={{ maxWidth: '200px' }} />,
    'src/assets/dummy-image-square.webp'
);

const App = () => {
    return (
        <>
            <ImageWithFallback
                src="src/assets/dummy-member.jpg"
                alt="Descriptive Text"
            />
        </>
    );
};

export default App;

Execute an application

Run the below command to execute an application after implementation of the codes.

npm run dev

Output:

react-broken-image

How To Check And Resolve Broken Images In React JS

Note: The output will be same for both of the approaches.




Reffered: https://www.geeksforgeeks.org


ReactJS

Related
JSX.Element vs ReactElement vs ReactNode JSX.Element vs ReactElement vs ReactNode
How to fix Next.JS Error: only absolute urls are supported? How to fix Next.JS Error: only absolute urls are supported?
Provide an Example Scenario where Portals are Useful in React Provide an Example Scenario where Portals are Useful in React
Add Styling to defaultValue in textarea in React Add Styling to defaultValue in textarea in React
What is NativeRouter in React Router? What is NativeRouter in React Router?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
20