Enhancing the user experience during navigation often involves creating smooth and visually appealing transitions between different views or application states. A powerful, relatively new tool provided directly by the browser to achieve this is the View Transitions API. This native browser API aims to simplify the process of animating changes in the Document Object Model (DOM), allowing developers to create seamless transitions between UI states with significantly less complex orchestration than traditional methods required.
Next.js team recently enabled the support for the ViewTransitions API in the app router, which is currently in experimental state. Let's dive deep into the usage of the ViewTransitions API, and how to use it in your application.
Read about the API here : https://nextjs.org/docs/app/api-reference/config/next-config-js/viewTransition
First step is to enable the experimental support for the feature as mentioned in the Next.js documentation by setting the experimental viewTransition
property to true
in your next.config.ts
file.
const nextConfig: NextConfig = {
experimental: {
viewTransition: true,
},
};
We will start from a blank app, and gradually add transitions to our components.
Let's create a basic app with a /
page and a /blog
page.
import Link from "next/link";
import { unstable_ViewTransition as ViewTransition } from "react";
export default function Home() {
return (
<div className="flex flex-col items-center justify-center h-screen text-center">
<h1 className="text-xl">Home Page</h1>
<h2>
<ViewTransition name="read-blog-page">
<span>Read our awesome blog</span>
</ViewTransition>
</h2>
<Link href="/blog">
<p>Go to blog page</p>
</Link>
</div>
);
}
import { unstable_ViewTransition as ViewTransition } from "react";
export default function Home() {
return (
<div className="flex flex-col p-12 h-screen text-center">
<h2>
<ViewTransition name="read-blog-page">
<span>Read our awesome blog</span>
</ViewTransition>
</h2>
</div>
);
}