How to blur the image on load in Next.js

·

3 min read

The heaviest parts of a webpage are images. Images slow down a website’s speed and make it load more slowly. The user experience might suffer as a result. As a result, I’ll show you in this post how to add hazy pictures as the page loads in Next in the simplest and quickest method possible. js.

I’m referring to the <Image /> component, one of Next.js’ impressive and potent technical offerings. It provides all the necessary SEO tools and automated image optimization, improving website performance and user experience.

Let’s get started!

Basic requirements

We’ll be using Tailwind CSS in this article. There will be a need for some basic Tailwind CSS knowledge.

Step 1: Install Tailwind CSS with Next.js

Initialize tailwind inside the Next.js application,

> npm install -D tailwindcss postcss autoprefixer
> npx tailwindcss init -p

Check out the complete guide for installing Tailwind CSS with Next.js on the official website.

Install the Aspect Ratio plugin for Tailwind

  • Install the plugin using npm,
npm install -D @tailwindcss/aspect-ratio

Then add the plugin to your tailwind.config.js,

// tailwind.config.js
module.exports = {
  theme: {
    // ...
  },
  corePlugins: {
    aspectRatio: false,
  },
  plugins: [
    require('@tailwindcss/aspect-ratio'),
    // ...
  ],
}

Step 2: Creating Blur Image Component

  • Create a new file components/BlurImage.js

  • Inside componets/BlurImage.js, add the following code,

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

  return (
    <a href={image.href} className="group">
      <div className="aspect-w-1 aspect-h-1 w-full overflow-hidden rounded-lg bg-gray-200 xl:aspect-w-7 xl:aspect-h-8">
        <Image
          alt=""
          src={image}
          layout="fill"
          objectFit="cover"
          className={`
              duration-700 ease-in-out group-hover:opacity-75
              ${
                isLoading
                  ? "scale-110 blur-2xl grayscale"
                  : "scale-100 blur-0 grayscale-0"
              })`}
          onLoadingComplete={() => setLoading(false)}
        />
      </div>
    </a>
  );
}

The picture will be blurred until it loads entirely.

Step 3: Importing Blur Image Component

Import the component,

import BlurImage from '../components/BlurImage'

Add the component to the page,

<BlurImage image={"https://domain.com/image.png"} />

This will blur the image on page load until the image loads completely.

How to Blur Images in Next.js Using Markdown

The remainder of Nikolov’s utilities makes it much easier to blur pictures within Markdown or MDX. All we have to do now is feed the plugin to our serialize method.

import imageMetaData from 'utils/imageMetadata'
import { serialize } from 'next-mdx-remote/serialize'


const components = {
    img: (props: any): React.ReactNode => (
        <Image {...props} layout="responsive" loading="lazy" />
    ),
}


function Post({ mdx }) {
    return (
        <>
            <MDXRemote
                {...mdx}
                components={components}
            />
        </>
}

export const getStaticProps = async context => {
  // Get your data from a database or any other source
  const markdown = getPostsFromDatabase();

  // convert your markdown to html with unified, rehype or remark
  const mdx = await serialize(markdown, {
      mdxOptions: {
          rehypePlugins: [imageMetaData],
      },
  })

  return {
    props: {
      mdx,
    },
  };
}

How to Blur Images in a Static Next.js Website

plaiceholder can also be used in a statically created Next.js webpage

export const getStaticProps = async context => {
  // Get your data from a database or any other source
  const data = getPostsFromDatabase();

  // Pass the image to plaiceholder
  const imageProps = await returnProps(data.thumbnailSrc);

  // Or maybe you have a gallery
  data.gallery = await Promise.all(
    data.gallery.map(async item => {
      const imageProps = await returnProps(item.imageSrc);

      // This will return the image a well as the needed plaiceholder
      // info in the same object within the array 🤯
      return { ...item, imageProps };
    })
  );

  return {
    props: {
      data,
      // This data will then be used by <Image> in our frontEnd
      thumbnail: imageProps
    },
  };
}

That’s all! Try loading your page. Before they lazy-load to view, your images should have a wonderful blur.

Read More