pwshub.com

Next.js View Transitions API

User expectations for web applications have evolved. Users expect seamless and smooth experiences when navigating between pages; they want the process to be as fluid as possible, and web applications have also evolved to meet user needs and expectations.

Case in point — Views Transitions API, a new and advanced browser feature for enhancing the user experience of web applications, particularly during navigation, making pages fluid and smooth.

The Views Transitions API is an amazing way to create animated transitions between website views quickly. Whether between DOM states in a single-page app (SPA) or navigation between documents in a multi-page app (MPA), the View Transitions API has animation covered.

This API allows developers to create smooth transitions between different views in a web application, providing a more native app-like experience.

Formerly, transitions in web applications required the use of Javascript, CSS, and a host of libraries. However, with the introduction of the Views Transitions API, it is much easier as there is now a standardized way of implementing transitions.

This cuts out the complexities, improves the performance of these animations, and gives a smoother feel.

I will explain how to use the View Transitions API in a Next.js application and cover the next-view-transitions library and its application. Afterwards, I will demonstrate how to implement transitions between different pages in a React app. I will also discuss some benefits of the Views Transitions API and compare it with manual implementation.

What is the next-view-transitions library?

The next-view-transitions library is a powerful tool that integrates the View Transitions API with Next.js, enabling software developers to create smooth transitions between various views in their applications easily.

This library reduces a lot of the complexity involved in setting up transitions, providing a clear and intuitive API for developers.

Key features of the next-view-transitions library include client and server-side transitions, simplified transition implementation for developers, and easy integration with existing Next.js projects.

Building apps with Next.js View Transitions API

To show the use of the View Transitions API in a Next.js application, we will create an app that shows seamless transitions between different pages. This application will have several pages with various types of content and a straightforward navigation menu.

The project application includes a navigation menu and several pages (Home, About, and Contact). Navigate between these pages to see the smooth transitions provided by the next-view-transitions library:

Animated transition showing the homepage of a web application with smooth navigation between pages using the View Transitions API.

Next.js installation and requirements

Before proceeding to build, some required tools must be installed. If you still need to install the following, please take some time to do so. The prerequisites for this tutorial are:

  • Node.js (v12 or higher)
  • npm or yarn (package managers)

If you have not installed any of these, please visit the official Node.js website.

Some basic understanding of React and Next.js will be a great plus!

After installing npm and Node.js, you can confirm your installation by running these commands:

node -v
npm -v

The installed versions of npm and Node.js will be displayed.

New Next.js project setup

Let’s create a new Next.js project using the required tools. Run the following command in your terminal to start a new Next.js application:

npx create-next-app@latest view-transitions-app

Click Yes to install all necessary dependencies. This command will create a new directory named view-transitions-app and set up a basic Next.js project.

Navigate to the newly created directory:

cd view-transition-app

Next, start the development server to verify that the project was set up correctly:

npm run dev

Open your browser and navigate to http://localhost:3000. You should see the default Next.js welcome page.

Installing next-view-transitions library

Installing the next-view-transitions library is the next step once we have our Next.js project configured. Use the command below to integrate the library into your project:

npm install next-view-transitions

This command will download and install the next-view-transitions library and its dependencies.

Creating basic React components

With the next-view-transitions library installed, let’s build some basic React components for our sample app. Create a new component directory inside the src directory. Inside the components directory, create two files: Navbar.tsx and PageContent.tsx.

The navigation bar:

import { Link } from 'next-view-transitions';
export const FlipNav = () => {
  return (
    <nav className="p-4 flex items-center justify-between relative">
      <NavLeft />
      <button className="px-4 py-2 bg-gradient-to-r from-violet-300 to-indigo-900 text-white font-medium rounded-md whitespace-nowrap">
        Sign up
      </button>
    </nav>
  );
};
const NavLeft = () => {
  return (
    <div className="flex items-center gap-6">
      <Link href="/">
        <Logo />
      </Link>
      <Link href="/about">About</Link>
      <Link href="/contact">Contact</Link>
      <Link href="/pricing">Pricing</Link>
      <Link href="/company">Company</Link>
    </div>
  );
};
const Logo = () => {
  return (
    <svg
      width="50"
      height="39"
      viewBox="0 0 50 39"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      className="fill-gray-800"
    >
      <path
        d="M16.4992 2H37.5808L22.0816 24.9729H1L16.4992 2Z"
        stopColor="#000000"
      ></path>
      <path
        d="M17.4224 27.102L11.4192 36H33.5008L49 13.0271H32.7024L23.2064 27.102H17.4224Z"
        stopColor="#000000"
      ></path>
    </svg>
  );
};

PageContent.tsx

This component renders the page content with a title and children:

'use client';
import { FC, ReactNode } from 'react';
interface PageContentProps {
  title: string;
  children: ReactNode;
}
const PageContent: FC<PageContentProps> = ({ title, children }) => {
  return (
    <div className="page-content">
      <h1>{title}</h1>
      <div>{children}</div>
      <style jsx>{`
        .page-content {
          padding: 2rem;
        }
        h1 {
          font-size: 2rem;
        }
      `}</style>
    </div>
  );
};
export default PageContent;

Implement transitions

With our basic components in place, we can implement transitions between pages using the next-view-transitions library. To do this, we will wrap our page components with a transition component provided by the library.


More great articles from LogRocket:

  • Don't miss a moment with The Replay, a curated newsletter from LogRocket
  • Learn how LogRocket's Galileo cuts through the noise to proactively resolve issues in your app
  • Use React's useEffect to optimize your application's performance
  • Switch between multiple versions of Node
  • Discover how to use the React children prop with TypeScript
  • Explore creating a custom mouse cursor with CSS
  • Advisory boards aren’t just for executives. Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

Layout.tsx

Open the app folder in the src directory and update the layout.tsx as follows:

import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import { ViewTransitions } from 'next-view-transitions';
import { FlipNav } from "@/components/NavBar";
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};
export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
      <ViewTransitions>        
        <html lang="en">
          <body className={inter.className}>
              <FlipNav />
              {children}
          </body>
        </html>
      </ViewTransitions>    
  );
}

Homepage

Next, update the file named page.tsx inside the src/app/ directory and update it as follows:

export default function Home() {
  return (
    <main className="p-24 text-center">
      <h1 className="text-5xl font-black">Home</h1>
    </main>
  );
}

For the pages About, Company, Contact, and Pricing, create a new file named page.tsx inside their respective directories (src/app/about, src/app/company, src/app/contact, src/app/pricing) and update the various files with the following:

About Page
import PageContent from '../../components/PageContent';
export default function About() {
  return (
    <PageContent title="">
        <main className="p-24 text-center">
          <h1 className="text-5xl font-black">About</h1>
        </main>
    </PageContent>
  );
}
...
Company
import PageContent from '../../components/PageContent';
export default function Company() {
  return (
     <PageContent title="">
        <main className="p-24 text-center">
          <h1 className="text-5xl font-black">Company</h1>
        </main>
     </PageContent>
  );
}
...
Contact
import PageContent from '../../components/PageContent';
export default function Contact() {
  return (
     <PageContent title="">
        <main className="p-24 text-center">
          <h1 className="text-5xl font-black">Contact Us</h1>
        </main>
     </PageContent>
  );
}
...
Pricing
import PageContent from '../../components/PageContent';
export default function Pricing() {
  return (
     <PageContent title="">
        <main className="p-24 text-center">
          <h1 className="text-5xl font-black">Pricing</h1>
        </main>
     </PageContent>
  );
}

Verify your transitions

After making these changes, restart your development server to see the transitions in action:

npm run dev

Benefits of next-view-transitions API

For developers and users alike, the next-view-transitions library provides tons of advantages.
The next-view-transitions library provides smoother transitions, making users’ experiences more interesting and visually appealing. It also gives the application a more polished, responsive feel.

The API provides simplified implementation. Developers can now concentrate on creating their apps rather than maintaining animations by using the next-view-transitions library, which removes the complexity involved in setting up transitions.

The library is performance-optimized. As a result, transitions are responsive, seamless, and consistent even on less capable devices.

Maintenance is an important factor when choosing what to build with and how to build. With the next-view-transitions library, developers can easily maintain and update their software and lower the chance of introducing bugs or performance concerns.

Comparison table of next-view-transitions and manual implementation

Here we compare the next-view-transitions library and a manual transition implementation using some parameters.

next-view-transitionsmanual implementation
Ease of useRelatively simple to understand, easy to get startedRequires custom code, which can be complex. May also require a high skill level to implement correctly
Performance o*ptimization*Already performance optimized thus resulting in better user experience across devicesHeavily dependent on the engineer/developer(s)
ConsistencyStandardized approach, high consistency across different forms of implementationConsistency depends on the engineer(s) involved and the implementation
Development timeFaster development time, particularly for simple transitionsMay take some time, depending on how complex the transition is

Conclusion

In this article, we explored how to set up a Next.js project, install the next-view-transitions library, and implement transitions between different pages in an application to create visually appealing and responsive web applications that delight users.

It is important to note that the View Transitions API makes it possible to animate totally different DOM elements that may not even be the same type.

Currently, the API is supported across browsers like Chrome, Edge, and Opera, while support for Safari is still in development and is something to look forward to!

Hey there, want to help make our blog better?

Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

Sign up now

Source: blog.logrocket.com

Related stories
2 weeks ago - Let’s discuss Svelte's history and key features, why you might choose it for your next project, and what sets it apart from other frameworks. The post Svelte adoption guide: Overview, examples, and alternatives appeared first on LogRocket...
4 days ago - Data surrounds us, but its raw form can be overwhelming and difficult to interpret. That's where data visualization comes in. It can help you take your data and turn it into charts and graphs that make sense at a glance. Among the many...
4 days ago - Auth.js makes adding authentication to web apps easier and more secure. Let's discuss why you should use it in your projects. The post Auth.js adoption guide: Overview, examples, and alternatives appeared first on LogRocket Blog.
1 month ago - In this tutorial, you will learn how to build an invoicing web app that allows users to add their bank information, manage a list of customers, and create and send invoices to customers. You'll also learn how to print and send React...
2 weeks ago - Learn about Zustand's simplistic approach to managing state and how it compares to existing tools such as Mobx and Redux. The post Zustand adoption guide: Overview, examples, and alternatives appeared first on LogRocket Blog.
Other stories
3 minutes ago - When you interact with web pages, a common task you’ll perform often is selecting text. Whether it's highlighting a section of a paragraph to copy, marking important parts of a document, or working with interactive features like...
1 hour ago - Hello, everyone! It’s been an interesting week full of AWS news as usual, but also full of vibrant faces filling up the rooms in a variety of events happening this month. Let’s start by covering some of the releases that have caught my...
2 hours ago - Nitro.js is a solution in the server-side JavaScript landscape that offers features like universal deployment, auto-imports, and file-based routing. The post Nitro.js: Revolutionizing server-side JavaScript appeared first on LogRocket Blog.
2 hours ago - Information architecture isn’t just organizing content. It's about reducing clicks, creating intuitive pathways, and never making your users search for what they need. The post Information architecture: A guide for UX designers appeared...
2 hours ago - Enablement refers to the process of providing others with the means to do something that they otherwise weren’t able to do. The post The importance of enablement for business success appeared first on LogRocket Blog.