Sling Academy
Home/Next.js/How to Set Placeholder for Image in Next.js

How to Set Placeholder for Image in Next.js

Last updated: January 01, 2024

Introduction

Managing image placeholders efficiently enhances the user experience by ensuring fast page loads and smooth transitions in Next.js applications.

Why Use Placeholders?

Image placeholders maintain the layout while the actual images are loading. This mitigates content layout shifts and improves perceived performance.

Next.js and Image Optimization

Next.js has a built-in Image component that enables automatic image optimization. From version 13 onward, it also introduces features for better handling of image placeholders.

Simple Placeholder with CSS

Let’s start with a straightforward approach, using CSS:

import Image from 'next/image';

export default function MyImageComponent() {
  return (
    <div className='image-container'>
      <Image
        src='/my-image.jpg'
        alt='My Image'
        layout='fill'
        objectFit='cover'
        placeholder='empty'
      />
    </div>
  );
}

In your CSS file:

.image-container::before {
  content: '';
  display: block;
  min-height: 100%;
  background: #E0E0E0;
}

Using Native Placeholder Attribute

Next.js Image component optionally accepts a ‘placeholder’ prop, which can be set to ’empty’ if no visual placeholders are shown:

import Image from 'next/image';

export default function MyImageComponent() {
  return (
    <Image
      src='/my-image.jpg'
      alt='Functional Placeholder for Image'
      layout='responsive'
      width={700}
      height={475}
      placeholder='empty'
    />
  );
}

The placeholder=’empty’ is a simple yet effective way to keep the space for your image without anything visible to the user until the image is fully loaded.

Using blurDataURL for Image Placeholder

Create a tiny, blurred version of the actual image serving as the placeholder:

import Image from 'next/image';
import myImage from '../public/my-image.jpg';

export default function MyImageComponent() {
  return (
    <Image
      src={myImage}
      alt='Blurry Placeholder'
      layout='responsive'
      width={700}
      height={475}
      placeholder='blur'
      blurDataURL='...' // your base64 encoded image here
    />
  );
}

Note: You need to generate a base64 encoded version of the image to use in the blurDataURL field.

Advanced Placeholder Handling

For advanced placeholder handling, consider on-the-fly image resizing services like Cloudinary or other third-party solutions:

Here’s how you can integrate such a service:

// Assuming you have set up a service for dynamically generating
// a base64 encoded version of the image
import Image from 'next/image';

export default function MyImageComponent() {
  // Dynamically get the base64 string for the blurry version from your service
  const blurDataURL = useBlurDataURL('/my-image.jpg');

  return (
    <Image
      src='/my-image.jpg'
      alt='Dynamic Placeholder'
      layout='responsive'
      width={700}
      height={475}
      placeholder='blur'
      blurDataURL={blurDataURL}
    />
  );
}

React Skeleton Screens as Placeholders

Skeleton Screens are another popular form of placeholders. They mimic the shape of the content that is loading and can be used while the images load.

Here’s an example:

import Image from 'next/image';
import Skeleton from 'react-loading-skeleton';

export default function MyImageWithSkeleton() {
  const [isLoading, setLoading] = useState(true);

  return (
    <>
      {isLoading ? (
        <Skeleton height={200} width={300} />
      ) : (
        <Image
          src='/my-image.jpg'
          alt='Image with Skeleton'
          layout='fixed'
          width={300}
          height={200}
          onLoadingComplete={() => setLoading(false)}
        />
      )}
    </>
  );
}

Ensure you have installed the ‘react-loading-skeleton’ package and manage the ‘isLoading’ state appropriately.

Conclusion

Setting an image placeholder in Next.js is seamless, enhancing the user experience while your visuals load gracefully. Discover the most suitable approach for your project requirements, and utilize Next.js’s native features or extend functionality with third-party tools for the best results.

Next Article: Next.js: Using Dynamic Import with a Named Export

Previous Article: Next.js: How to Access Files in the Public Folder

Series: The First Steps to 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