Skip to content

Instantly share code, notes, and snippets.

@codegino
Last active November 17, 2021 09:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codegino/b9ed69fec8495c5024ef925c432bf1f2 to your computer and use it in GitHub Desktop.
Save codegino/b9ed69fec8495c5024ef925c432bf1f2 to your computer and use it in GitHub Desktop.
Next Image with placeholder and error handler
function CustomImage({...props}: ImageProps) {
const [src, setSrc] = React.useState(props.src);
return (
<Image
onError={() => setSrc('/assets/image-error.png')}
placeholder="blur"
blurDataURL="/assets/image-placeholder.png"
{...props}
src={src}
/>
);
}
import Image, {ImageProps} from 'next/image';
function CustomImage({alt, ...props}: ImageProps) {
const [src, setSrc] = React.useState(props.src);
return (
<Image
{...props}
src={src}
alt={alt}
onError={() => setSrc('/assets/image-error.png')}
placeholder="blur"
blurDataURL="/assets/image-placeholder.png"
/>
);
}
import React from 'react';
import { CustomImage } from '../components/CustomImage';
export default function IndexPage() {
return (
<CustomImage
src="https://i.imgur.com/gf3TZMr.jpeg"
layout="fixed"
height={500}
width={700}
alt={'alt'}
/>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment