In order to achieve the desired effect, server side rendering is necessary. This ensures that images start loading before you navigate to a new page. In Next.js, all pages accessed through a Link element are pre-rendered while you remain on the current page containing the <Link>
element.
To create the effect, first set the image's CSS position to fixed
, then create a transition that scales the image to width: 100%
and height: 100%
with a 500ms duration. Also, implement a timeout function to route you to the next page where the image is already loaded as a background. Additionally, include a
<Link href="/next-page" />
somewhere to ensure the page is pre-rendered.
On the first page:
const router = useRouter();
const [transitionStarted, setTransitionStarted] = useState<boolean>(false);
function handleClick() {
setTransitionStarted(true);
setTimeout(() => {
router.push("/next-page");
}, 500)
}
return (
<div>
<Link className="hidden" href="/next-page" />
<Image
className={`duration-500 ${transitionStarted ? "fixed w-full h-full top-0 left-0" : "<initial image sizing and styles>"}`}
onClick={handleClick}>
src="path-to-image"
fill
alt="image link" />
</div>
)
On the next page:
return (
<div>
<Image className="fixed w-full h-full top-0 left-0" fill alt="image used as background on next page" />
</div>
)
I have provided the example in tailwindcss for better readability, but this can be achieved with any other CSS library. To ensure a smooth transition, synchronize the durations of the transition and setTimeout so that the redirection only occurs after the transition is complete and both images on both pages are identical.
I hope this answers your question. You can refer to the tailwindcss documentation for more details on the classes used in the example.