You can create a custom image component that extends the built-in next/image
and adds the fallback logic if the image fails to load by triggering the onError
callback.
import React, { useState } from 'react';
import Image from 'next/image';
const ImageWithFallback = (props) => {
const { src, fallbackSrc, ...rest } = props;
const [imgSrc, setImgSrc] = useState(src);
return (
<Image
{...rest}
src={imgSrc}
onError={() => {
setImgSrc(fallbackSrc);
}}
/>
);
};
export default ImageWithFallback;
Then, you can directly use the custom component instead of next/image
as follows:
<ImageWithFallback
key={videoId}
layout="fill"
src={`https://i.ytimg.com/vi/${videoId}/maxresdefault.jpg`}
fallbackSrc={`https://i.ytimg.com/vi/${videoId}/hqdefault.jpg`}
/>
Passing a key
prop to trigger a re-render on videoId
change.