0 day streak
javascript / beginner
Snippet

Handling Broken Image URLs with an onError Fallback State

Network requests for remote images can fail if links break. Listening to the standard onError event lets you catch loading failures and update local state to display a safe fallback image placeholder.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { useState } from 'react';
export function AvatarImage({ src }) {
const [hasError, setHasError] = useState(false);
const fallbackSrc = '/images/placeholder.png';
return (
<img
src={hasError ? fallbackSrc : src}
alt="User profile"
onError={() => setHasError(true)}
/>
);
}
react
Breakdown
1
const [hasError, setHasError] = useState(false);
Tracks whether the primary image URL encountered a load error.
2
src={hasError ? fallbackSrc : src}
Dynamically sets the source attribute to the fallback URL if an error occurred.
3
onError={() => setHasError(true)}
Triggered automatically by the browser when the image fails to load, triggering the state change.