Handling Image Errors in React

While working on a take-home assessment this week, I encountered an issue that I’d never thought of before: what happens when an image src is broken?

It’s not cute. Also, if you are using any sort of formatting or styling on your page, it can really throw a wrench into all of it.

For my take-home assessment, one of the tasks required me to iterate through some data and create a “team roster,” which each team member having a card that contained a profile picture, along with their name, title, and bio. I wanted all of the images to be a consistent size, which worked beautifully with CSS until…I realized one of the image src URLs was broken. The broken image icon of doom showed up on the screen and messed up all of my hard work and formatting.

What is a poor programmer to do? Here, I’m going to step through the process of fixing this little problem in your React applications!

Step 1: Choose a Default Image

With a face like that, who cares if the image is broken, right?

Step 2: Make Sure to Always Include an Alt Property

<img src="www.dog-pics.com" alt="funny picture of a corgi">

Step 3: Create Function to Call on Default Image

const addDefaultImg = ev => {
ev.target.src = "default-dog.jpg"

This function, addDefaultImg, takes an event (an image tag), and changes the src to the default image you have already selected. Pretty simple!

Step 4: Use onError to Call on Function

<img src="www.dog-pics.com" alt="funny picture of a corgi" onError={addDefaultImg}>

Note: I used all functional components. If using a class component, make sure to use this.addDefaultImg.

And that’s it! A super quick way to add a default image in case one of yours breaks and you don’t catch it quickly. Happy coding!

Blaire is a musical theatre performer who also moonlights as a full-stack software engineer. https://www.linkedin.com/in/blaire-baker