Skip to content

Commit 3dcefb0

Browse files
committed
fix(cacheing): Handle cases where image was cached
1 parent 3f97776 commit 3dcefb0

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

src/index.tsx

+18
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,23 @@ export default function NextImageFromFile(props: NextImageFromFileProps) {
99
width: number;
1010
height: number;
1111
}>(null);
12+
const imageRef = React.useRef<null | HTMLImageElement>(null);
13+
14+
// In case the image was cached and won't trigger onLoad
15+
// read width and height from the ref
16+
React.useEffect(() => {
17+
// image already there or not rendered yet?
18+
if (image || !imageRef.current) return;
19+
// image has not been loaded yet?
20+
if (imageRef.current.complete === false) return;
21+
// width and height are 0 so the image has not been painted yet?
22+
if (imageRef.current.width === 0 || imageRef.current.height === 0) return;
23+
24+
setImage({
25+
width: imageRef.current.width,
26+
height: imageRef.current.height,
27+
});
28+
});
1229

1330
// Fall back to regular next/image if all necessary props are given
1431
if (typeof props.src !== "string" || (props.width && props.height)) {
@@ -20,6 +37,7 @@ export default function NextImageFromFile(props: NextImageFromFileProps) {
2037
return (
2138
<img
2239
src={props.src}
40+
ref={imageRef}
2341
onLoad={(event) => {
2442
const target = event.target as HTMLImageElement;
2543
setImage({ width: target.width, height: target.height });

0 commit comments

Comments
 (0)