Introduction
When you want to add a picture to a website you write a simple line such as this:
- <img src="smiley.gif" alt="Smiley face">
- <img src={require('../images/image-name.png')} />

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.
- import React from 'react';
- class CustomImg extends React.Component {
- render() {
- let image_path = '';
- try {
- image_path = require('../../../images/' + this.props.src);
- } catch(err){
- image_path = require('../../../images/no_image.svg'); //set default image path
- }
- return (
- <img width={this.props.width} src={image_path} className={this.props.className} alt={this.props.alt} />
- );
- }
- }
- export default CustomImg;
Step 3
Use the CustomImg component wherever the image is required to display.
- import React, { Component } from 'react';
- import CustomImg from '../../Global/CustomImg/CustomImg';
- class App extends Component {
- render() {
- return (
- <React.Fragment>
- <div>
- <CustomImg src="sample.png" className="container-close float-right" alt="sample Image" />
- </div>
- </React.Fragment >
- );
- }
- }
- export default App;
Summary
I hope it helps you!!!.

Join the conversation! Your thoughts help the community grow.