Handling Image Errors in React

thequeenbeebs
3 min readAug 11, 2021

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

Decide on the default image that will replace the SRC if your image is broken! You can choose whatever you like: the silhouette of a head, an “oops this image is broken sign,” or even a corgi with its snoot in the middle of a slice of bread:

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

Step 2: Make Sure to Always Include an Alt Property

This is common knowledge, but I just wanted to remind you to always include the alt property in all img tags you use. This is important not only for situations where the image is broken, but it is also crucial for screen readers to make your application more accessible. If you’re not familiar, this is what it looks like:

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

Step 3: Create Function to Call on Default Image

Now, we’re going to create a function inside our React component that will change the SRC to our selected 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

In order to call on that function, we are going to use the onError property that React has in its framework, which is called every time there is an error when a tag is rendered (i.e. when the src is broken). Check it out:

<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!

--

--

thequeenbeebs

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