Sling Academy
Home/Next.js/Ways to Set a Fallback Image in Next.js

Ways to Set a Fallback Image in Next.js

Last updated: January 01, 2024

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.

Previous Article: How to Import & Display Local Images in Next.js

Series: Fetching and Rendering Data in Next.js

Next.js

Related Articles

You May Also Like

  • Solving Next.js Image Component Error with CSS Classes
  • How to Use MUI (Material UI) in Next.js 14
  • Fixing Data Update Issues in Next.js Production
  • Fixing Next.js Undefined ENV Variables in Production Build
  • Solving Next.js SyntaxError: Unexpected token ‘export’
  • Next.js Error: Found Page Without a React Component as Default Export – How to Fix
  • Fixing Next.js Error: Blank Page on Production Build
  • Fixing Next.js Error when Importing SVGs: A Step-by-Step Guide
  • Next.js Issue: useEffect Hook Running Twice in Client
  • Fixing ‘self’ is not defined error in Next.js when importing client-side libraries
  • How to Dockerize a Next.js App for Production
  • How to set up Next.js with Docker Composer and Nginx
  • Solving Next.js CORS Issues: A Comprehensive Guide
  • Fixing Next.js Hydration Mismatch Error in Simple Ways
  • Next.js Error: Cannot use import statement outside a module
  • Next.js: How to Access Files in the Public Folder
  • Fixing Next.js Import CSS Error: A Simple Guide
  • Fixing LocalStorage Not Defined Error in Next.js
  • Fixing Next.js Error: No HTTP Methods Exported