check and resolve broken images in reactjs

How To Check And Resolve Broken Images In React JS

Most Frontend and JS developers are shifting to ReactJS. At the beginner level, they face some primary issues and get panic.

I have addressed one of the most common issues of “broken image in ReactJS” to help beginners. The error appears in several ways, like a missing image key or a broken image in the database.

Let’s break it down step by step and resolve each case with clean, readable code.


Starter Code

Here’s a basic example that displays a list of blog cards using dummy image links. One of them is broken on purpose, and another doesn’t have an image key.

import './blogs-module.css'
const blogs = [
{
id: '01',
title: 'How to learn Javascript',
cover:
'https://images.unsplash.com/photo-1648737966769-98fa88fe66bb?ixlib=rb-1.2.1&ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=872&q=80',
},
{
id: '02',
title: 'ReactJS beginners guide',
cover:
'https://images.unsplash.com/photo-6f2b6890edc5?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80',
},
{
id: '03',
title: 'HTML semantic tags',
cover:
'https://images.unsplash.com/photo-1655838774838-4a1322530d52?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwzNHx8fGVufDB8fHx8&auto=format&fit=crop&w=600&q=60',
},
{
id: '04',
title: 'Customize Radio Button',
},
]
function Blogs() {
return (
<div className="container blogs-page">
<h2 className="page-title">Popular Blogs</h2>
<div className="blog-section">
{blogs.map(({ id, title, cover }) => (
<div className="blogs" key={id}>
<img src={cover} alt="cover image" />
<h3>{title}</h3>
</div>
))}
</div>
</div>
)
}
export default Blogs
Broken Image Starter

You’ll notice that in the rendered output, the 2nd image is broken, and the 4th doesn’t load any image at all.

Let’s solve these one by one.


🛠 Find the broken image in ReactJS

Before we dive into the fix, let’s understand what’s going wrong.

  • On the 2nd blog card, the image URL is either invalid or broken.
  • On the 4th card, the image key is missing from the data entirely.

This results in an awkward and broken UI that you definitely don’t want in production.


✅ Solutions to Broken Image Problems

Let’s fix them with clean and efficient React code.


1. Fix the no-image key issue (missing cover field)

When the cover key is missing, we can easily show a fallback image using a ternary operator. Just define a placeholderImage and check if cover exists.

function Blogs() {
const placeholderImage =
'https://images.unsplash.com/photo-1597484661973-ee6cd0b6482c?ixlib=rb-1.2.1&auto=format&fit=crop&w=774&q=80'
return (
<div className="container blogs-page">
<h2 className="page-title">Popular Blogs</h2>
<div className="blog-section">
{blogs.map(({ id, title, cover }) => (
<div className="blogs" key={id}>
<img src={cover ? cover : placeholderImage} alt="cover image" />
<h3>{title}</h3>
</div>
))}
</div>
</div>
)
}

Now, the 4th blog card will no longer look broken—it’ll show a beautiful fallback image instead. Nice and smooth.


2. Fix the broken image URL issue (broken cover value)

Even when a cover is provided, the image can still break due to a wrong or expired URL. Here’s where the onError handler comes in handy.

We’ll update our code to attach an onError event to each image tag and replace the source dynamically when loading fails.

const Blogs = () => {
const placeholderImage =
'https://images.unsplash.com/photo-1511285605577-4d62fb50d2f7?ixlib=rb-1.2.1&auto=format&fit=crop&w=876&q=80'
const onImageError = (e) => {
e.target.src = placeholderImage
}
return (
<div className="container blogs-page">
<h2 className="page-title">Popular Blogs</h2>
<div className="blog-section">
{blogs.map(({ id, title, cover }) => (
<div className="blogs" key={id}>
<imgsrc={cover ? cover : placeholderImage}
alt="cover image"
onError={onImageError}
/>
<h3>{title}</h3>
</div>
))}
</div>
</div>
)
}

Boom. Now we’re covered for both cases—when the image key is missing and when the image URL is broken.


3. Bonus: Create a Reusable FallbackImage Component 🚀

If you’re dealing with images across multiple components, it's better to extract the logic into a separate component. This improves readability and reusability.

Here’s a simple fallback image component:

const FallbackImage = ({ src, alt }) => {
const placeholder =
'https://images.unsplash.com/photo-1581291519195-ef11498d1cf5?auto=format&fit=crop&w=800&q=80'
const handleError = (e) => {
e.target.src = placeholder
}
return <img src={src || placeholder} alt={alt} onError={handleError} />
}

Now use it like this:

<FallbackImage src={cover} alt="cover image" />

Use this technique in production-grade apps to keep your codebase clean and modular.


🎨 Add CSS to the Component

This part isn’t mandatory, but who doesn’t like a pretty UI?

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;600&display=swap');
body {
box-sizing: border-box;
color: #220f5f;
font-family: 'Poppins', sans-serif;
}
.container {
width: 100%;
max-width: 1000px;
padding: 0 15px;
margin: 0 auto;
margin-top: 70px;
}
.blog-section {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 20px;
}
.blogs {
border: 1px solid gainsboro;
border-radius: 4px;
}
.blogs img {
width: 100%;
object-fit: cover;
height: 180px;
}
.blogs h3 {
padding: 5px 8px;
cursor: pointer;
font-size: 16px;
font-weight: 600;
}

Want to make it responsive? Just update the grid to grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));.


Final Thoughts

Broken images are small issues that leave a bad first impression. But thankfully, React gives us clean and powerful ways to fix them with just a few lines of code.

  • Use a ternary check when the image key might be missing.
  • Use an onError handler when the URL might be broken.
  • Extract the logic into a reusable component for better DX (developer experience).

If you’ve learned something new, share this article with your frontend friends. Help them ship fewer broken UIs 😉

Read Next

Codevertiser Magazine

Subscribe for a regular dose of coding challenges and insightful articles, delivered straight to your inbox