Images are the heaviest components of a website. Images prevent a website from loading faster and decrease its performance. This might result in a poor user experience. Therefore, in this article, I will teach you the simplest and easiest way to add blurry images on page load in Next.js.
Next.js provides an impressive and powerful piece of engineering, I am talking about the <Image />
component. It offers automatic image optimization and all the essential SEO options, resulting in a better user experience and website performance.
Let’s get started!
Prerequisites
- In this article, I will be using Tailwind CSS. Basic knowledge to Tailwind CSS will be required.
That’s it nothing more required.
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 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 image will be blurred until it loads completely.
Step 3: Importing Blur Image Component
- Import the component,
import BlurImage from '../components/BlurImage'
- Add the component to the page,
<BlurImage image={"https://example.com/assets/dog.png"} />
This will blur the image on page load until the image loads completely.
Check out the live example: blur-img.vercel.app
Thanks for reading
Follow me on Twitter
Thanks for reading!