Skip to content

Commit 8c7434a

Browse files
Feat: add onImgLoadError callback prop
1 parent a859dbd commit 8c7434a

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

README.md

+16
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,22 @@ A function to be executed after the image is loaded
378378
src="dino-reichmuth-1.jpg"
379379
onImgLoad={(event)=>{ console.log(event); }}/>
380380
```
381+
382+
### onImgLoadError
383+
384+
###### Type: **function ({ event, setLoaded }) {}** | Default: **undefined**
385+
386+
A function to be executed after the image is loaded
387+
388+
```jsx
389+
<Img
390+
src="dino-reichmuth-1.jpg"
391+
onImgLoadError={({ event, setLoaded })=>{
392+
setLoaded(true) // declares whether the image is loaded or not, if `true` - loaded - then assign the proper styles otherwise no need for the loaded styles (useful in-case u added a new src for the image throguh the fallback and want to apply the styles), by default setLoaded(false) is triggered in-case of failure.
393+
console.log(event);
394+
}} />
395+
```
396+
381397
### width
382398

383399
###### Type: **String** (e.g. 300px, 20vw) | Default: **undefined**

src/Img.js

+11-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ function Img(props) {
2424
const {
2525
quality = imagesQuality, src, params = imagesParams,
2626
layout = imagesLayout, objectFit = imagesObjectFit,
27-
lowPreviewQuality = imagesLowPreviewQuality, onImgLoad,
27+
lowPreviewQuality = imagesLowPreviewQuality, onImgLoad, onImgLoadError,
2828
width, height, doNotReplaceURL = imagesDoNotReplaceURL,
2929
className, alt, transitionDuration = imagesTransitionDuration,
3030
style = {}, ssr = imagesSsr, children, background, objectPosition = imagesObjectPosition,
@@ -68,6 +68,14 @@ function Img(props) {
6868
}
6969
};
7070

71+
const onImageLoadError = (event) => {
72+
setLoaded(false)
73+
74+
if (typeof onImgLoadError === 'function') {
75+
onImgLoadError({ event, setLoaded });
76+
}
77+
}
78+
7179
const processImage = (update, windowScreenBecomesBigger) => {
7280
const options = {
7381
src,
@@ -157,6 +165,7 @@ function Img(props) {
157165
onLoad={onImageLoad}
158166
loading={lazyload ? 'lazy' : 'eager'}
159167
alt={_alt}
168+
onError={onImageLoadError}
160169
{...computeImageSize(layout, width, height)}
161170
/>
162171
) : (
@@ -168,6 +177,7 @@ function Img(props) {
168177
style={computeImageStyles(loaded, transitionDuration, objectFit, objectPosition, !previousSrc.current)}
169178
className={classes.ciSsgImage}
170179
loading={lazyload ? 'lazy' : 'eager'}
180+
onError={onImageLoadError}
171181
/>
172182
)}
173183

0 commit comments

Comments
 (0)