Next/Image Loading and Fallback component?
Unanswered
American black bear posted this in #help-forum
American black bearOP
Hello 👋
I'm trying to create a skeleton-like loading and fallback component to be used alongside next/image. Is there a commonly used pattern for something like this? Googling just seems to show replacing the source onError as a fallback - But my fallback is just a styled html element so I'm not sure how this works.
This is roughly what I'm trying to do - But obviously, if the
Any help would be appreciated 🙂
*Edit - Assets are being requested from a CDN, they're not hosted in my repository - In case that changes anything
I'm trying to create a skeleton-like loading and fallback component to be used alongside next/image. Is there a commonly used pattern for something like this? Googling just seems to show replacing the source onError as a fallback - But my fallback is just a styled html element so I'm not sure how this works.
This is roughly what I'm trying to do - But obviously, if the
Image is never rendered to the page in the first place, the error/loading callbacks won't ever fire.Any help would be appreciated 🙂
*Edit - Assets are being requested from a CDN, they're not hosted in my repository - In case that changes anything
const Something = ({ assetPath }) => {
const [imageError, setImageError] = useState<boolean>(false);
const [imageLoaded, setImageLoaded] = useState<boolean>(false);
return (
<div>
{imageLoaded || !imageError ? (
<Image
src={assetPath}
width={100}
height={50}
alt=""
className="rounded"
onError={() => setImageError(true)}
onLoadingComplete={() => setImageLoaded(true)}
/>
) : (
<span className="block w-[100px] h-[50px] bg-primary rounded"></span>
)}
</div>
);
};