Error Handling While Use Image Render In React

Introduction

 
When you want to add a picture to a website you write a simple line such as this:
  1. <img src="smiley.gif" alt="Smiley face">  
ReactJs has the in-built function to render the local image with require ('pathname') in webpack.
  1. <img src={require('../images/image-name.png')} /> 
In order to use this default functionality, we need to provide a physical path as a parameter. So whenever your application builds a webpack, it is responsible for getting the image from the specified physical path. But in case no file is available on the specified path then it will throw an error.
 

Solution

 
You need to error handle over this point, so that you can create custom control or component to handle this error.
 
Step 1
 
Choose your default image which you want to display when the image is not found, and place a default image on the desired folder in your application.
 
Step 2
 
For error handling you need to create a custom component as below.
  1. import React from 'react';  
  2.   
  3. class CustomImg extends React.Component {  
  4.     render() {  
  5.         let image_path = '';  
  6.         try {  
  7.             image_path = require('../../../images/' + this.props.src); 
  8.         } catch(err){  
  9.             image_path = require('../../../images/no_image.svg');  //set default image path
  10.         }  
  11.         return (  
  12.             <img width={this.props.width} src={image_path} className={this.props.className} alt={this.props.alt} />  
  13.         );  
  14.     }  
  15. }  
  16.   
  17. export default CustomImg;   
Step 3
 
Use the CustomImg component wherever the image is required to display.
  1. import React, { Component } from 'react';  
  2. import CustomImg from '../../Global/CustomImg/CustomImg';  
  3.   
  4. class App extends Component {  
  5.     render() {  
  6.         return (  
  7.             <React.Fragment>  
  8.                 <div>  
  9.                     <CustomImg src="sample.png" className="container-close float-right" alt="sample Image" />  
  10.                 </div>  
  11.             </React.Fragment >  
  12.         );  
  13.     }  
  14. }  
  15.   
  16. export default App; 
 

Summary

 
CustomImg component is a customized component which can handle the error of rendering an image using React. You can customize this component as per your convenience by using props functionality. Right now only className, width, src, alt properties are handled dynamically.
 
I hope it helps you!!!.