-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathuseImageErrorFallback.ts
More file actions
37 lines (31 loc) · 1.05 KB
/
Copy pathuseImageErrorFallback.ts
File metadata and controls
37 lines (31 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { useEffect, type RefObject } from 'react';
/*
* Flag images that fail to load so CSS can swap in a broken-image placeholder.
*/
export const useImageErrorFallback = (
containerRef: RefObject<HTMLElement | null>
) => {
// listen for errors
useEffect(() => {
const container = containerRef.current;
if (!container) return;
const handleImageError = (e: Event) => {
const target = e.target as HTMLElement;
if (target && target.tagName && target.tagName.toLowerCase() === 'img') {
target.classList.add('error');
}
};
container.addEventListener('error', handleImageError, true);
// handle <img> elements that emitted an error event before we could set up a listener
const images =
container.querySelectorAll<HTMLImageElement>('img:not(.error)');
images.forEach((img) => {
if (img.complete && img.naturalHeight === 0) {
img.classList.add('error');
}
});
return () => {
container.removeEventListener('error', handleImageError, true);
};
}, [containerRef]);
};