Ways to Set a Fallback Image in Next.js

Updated: January 1, 2024 By: Guest Contributor Post a comment

Explore some different ways to set a fallback image in Next.js

Image Component with onError

The Image component in Next.js supports the onError event handler that can be used to change the image source if the initial source fails to load.

The process is as follows:

  1. Create a state to manage the image source.
  2. Set the initial state to your primary image URL.
  3. Use the onError event to change the image source to your fallback image when an error occurs.

Let’s see an example for more clarity:

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

const MyComponent = () => {
    const [imgSrc, setImgSrc] = useState('/primary-image.jpg');

    return (
        <Image
            src={imgSrc}
            alt='Descriptive alt text'
            width={500}
            height={300}
            onError={() => setImgSrc('/fallback-image.jpg')}
        />
    );
};

export default MyComponent;

Pros: Easy to implement; No extra libraries or components required.

Cons: Inline error handling can become unmanageable in large applications.

Custom Image Component

Create a reusable custom Image component that handles the fallback internally.

The steps to follow:

  1. Define a new custom Image component.
  2. Use the useState and useEffect hooks to handle errors and switch to the fallback image.
  3. Use your Custom Image component wherever you need an image with a fallback.

A small code example:

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

const CustomImage = ({ src, fallbackSrc, ...props }) => {
    const [source, setSource] = useState(src);

    const handleError = () => {
        setSource(fallbackSrc);
    };

    return (
        <Image
            {...props}
            src={source}
            onError={handleError}
        />
    );
};

export default CustomImage;

Pros: Reusable component; Encapsulates the error handling logic.

Cons: Slightly more complex than the basic onError method.

Static Import with Placeholder Blur

Next.js allows you to statically import images and use a placeholder while the main image is loading. This method involves using the ‘blurDataURL’ property, which is a small, blurred version of your image to be used as a placeholder before the main image loads.

Here’re the main points:

  1. Statically import both your primary image and the fallback image.
  2. Assign the imported fallback image’s blurDataURL to the primary image’s placeholder.
  3. Set the placeholder property to ‘blur’ on the primary image.

Example:

import primaryImage from '../public/primary-image.jpg';
import fallbackImage from '../public/fallback-image.jpg';
import Image from 'next/image';

const MyComponent = () => {
    return (
        <Image
            src={primaryImage}
            alt='Descriptive alt text'
            placeholder='blur'
            blurDataURL={fallbackImage}
            width={500}
            height={300}
        />
    );
};

export default MyComponent;

Pros: Native Next.js feature; Utilizes built-in image optimization.

Cons: Requires preloading images; Not suitable for dynamically sourced images.

Final Words

In conclusion, setting a fallback image in Next.js 13 can be achieved in various ways, each with its own set of advantages and trade-offs. The approach should be chosen based on the specific use case and requirements of the application. Whether using a simple onError handler, creating a custom component, or leveraging static import with a placeholder blur, Next.js provides developers with flexible options to ensure a robust and user-friendly image loading experience.