In this article, we learn how to show the default image OnError in react.
The OnError event is triggered if an error occurs in images or files while loading.
Here we take an image tag to show the image and give the URL image which will we show in the output.
Now the image will render the OnLoad event and take the default image URL which image we will show the OnError event.
<img src={IMAGE_1} onLoad={imageOnLoadHandler} onError={imageOnErrorHandler} alt="www.kindacode.com" />
When we get some error on a given image URL that time OnError event fires and shows the default image.
const imageOnLoadHandler = (event) => { console.log( `The image with url of ${event.currentTarget.src} has been loaded` ); if (event.currentTarget.className !== "error") { event.currentTarget.className = "success"; } } const imageOnErrorHandler = (event) => { event.currentTarget.src = FALLBACK_IMAGE; event.currentTarget.className = "error"; };
My file looks like this,
import './App.css'; function App() { const IMAGE_1 = "https://test.kindacode.com/this-image-does-not-exist.jpeg"; const IMAGE_2 = "https://www.kindacode.com/wp-content/uploads/2021/08/fried-chicken.jpeg"; const FALLBACK_IMAGE = "https://www.kindacode.com/wp-content/uploads/2021/08/oops.png"; const imageOnLoadHandler = (event) => { console.log( `The image with url of ${event.currentTarget.src} has been loaded` ); if (event.currentTarget.className !== "error") { event.currentTarget.className = "success"; } }; const imageOnErrorHandler = (event) => { event.currentTarget.src = FALLBACK_IMAGE; event.currentTarget.className = "error"; }; return ( <div className="container"> <img src={IMAGE_1} onLoad={imageOnLoadHandler} onError={imageOnErrorHandler} alt="www.kindacode.com" /> <img src={IMAGE_2} onLoad={imageOnLoadHandler} onError={imageOnErrorHandler} alt="www.kindacode.com" /> </div> ); } export default App;
Show our image render on OnLoad event or OnError event we give some CSS.
.success { border: 5px solid green; } .error { border: 5px solid red; }
Here, the red-bordered image is rendered on the OnError event and the green-bordered image is rendered on the OnLoad event.
Output:-