Fallback image component

By Hunter Becton on May 25, 2022

import { useEffect, useState } from 'react'
import Image from 'next/image'

export const FallbackImage = ({ src, ...rest }) => {
  const [imgSrc, setImgSrc] = useState(src)

  useEffect(() => {
    setImgSrc(src)
  }, [src])

  return (
    <Image
      {...rest}
      src={imgSrc ? imgSrc : '/images/not-found.png'}
      onError={() => {
        setImgSrc('/images/not-found.png')
      }}
    />
  )
}

How to use

Use this component like you would the Next.js component, passing in the required props outlined in the Next.js image documentation. Then include an image you'd like to use as a fallback in the public folder in your Next.js application.