Fade in Next.js Images on load - example or plugin?
Hey there! This is actually a Next.js/React question rather than a Sanity-specific one, but I'm happy to help since many Sanity users work with Next.js!
For fading in Next.js <Image> components when they load, here's a common approach using the onLoad callback (which replaced the deprecated onLoadingComplete):
import Image from 'next/image';
import { useState } from 'react';
function MyImage({ src, alt }) {
const [isLoaded, setIsLoaded] = useState(false);
return (
<Image
src={src}
alt={alt}
width={800}
height={600}
onLoad={() => setIsLoaded(true)}
className={`transition-opacity duration-500 ${
isLoaded ? 'opacity-100' : 'opacity-0'
}`}
/>
);
}With Tailwind CSS (which you mentioned), you can make it even cleaner:
import Image from 'next/image';
import { useState } from 'react';
export default function FadeInImage({ src, alt, ...props }) {
const [isLoaded, setIsLoaded] = useState(false);
return (
<div className="relative">
<Image
src={src}
alt={alt}
onLoad={() => setIsLoaded(true)}
className={`
transition-opacity duration-700 ease-in-out
${isLoaded ? 'opacity-100' : 'opacity-0'}
`}
{...props}
/>
</div>
);
}If you're using Sanity images specifically, you'd typically use @sanity/image-url to generate the URLs:
import imageUrlBuilder from '@sanity/image-url';
import Image from 'next/image';
import { useState } from 'react';
const builder = imageUrlBuilder(sanityClient);
function SanityImage({ image, alt }) {
const [isLoaded, setIsLoaded] = useState(false);
return (
<Image
src={builder.image(image).width(800).url()}
alt={alt || image.alt || ''}
width={800}
height={600}
onLoad={() => setIsLoaded(true)}
className={`transition-opacity duration-500 ${
isLoaded ? 'opacity-100' : 'opacity-0'
}`}
/>
);
}You can adjust the duration-500 (500ms) to whatever timing feels right for your design. Some people prefer duration-700 or duration-300 depending on the feel they want.
Hope this helps! Let me know if you need any clarification on integrating this with your Sanity content.
Show original thread14 replies
Was this answer helpful?
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.