10

I'm trying to make a page transition with Next.js v14 but no success.

No error is shown, the animation just does't work. I guess it's because the layout.tsx is rendered on the server. But how can I fix it?

My layout.tsx code (root level):

import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import Sidebar from "@/components/Sidebar";
import Breadcrumbs from "@/components/Breadcrumbs";
import Topbar from "@/components/Topbar";
import PageTransitionEffect from "@/components/PageTransitionEffect";

const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body className={`${inter.className} flex flex-col min-h-screen`}>
        <Topbar />

        <div className="bg-gray-800 text-gray-200 flex flex-grow overflow-x-hidden px-0">
          <Sidebar />

          <div className="flex-col mx-auto flex w-full py-6 px-4 sm:px-6 md:px-14">
            <Breadcrumbs />

            <PageTransitionEffect>{children}</PageTransitionEffect>
          </div>
        </div>
      </body>
    </html>
  );
}

My PageTransitionEffect component code:

"use client";

import { motion } from "framer-motion";

const PageTransitionEffect = ({ children }: { children: React.ReactNode }) => {
  const variants = {
    hidden: { opacity: 0, x: -200, y: 0 },
    enter: { opacity: 1, x: 0, y: 0 },
    exit: { opacity: 0, x: 0, y: -100 },
  };

  return (
    <motion.div
      initial="hidden"
      animate="enter"
      exit="exit"
      variants={variants}
      transition={{ type: "linear" }}
    >
      {children}
    </motion.div>
  );
};

export default PageTransitionEffect;

Edit #1 (warning message):

Warning: Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported.
    at FrozenRouter (webpack-internal:///(ssr)/./src/components/PageTransitionEffect/index.tsx:21:70)
    at div
    at MotionComponent (webpack-internal:///(ssr)/./node_modules/framer-motion/dist/es/motion/index.mjs:49:65)
    at PopChildMeasure (webpack-internal:///(ssr)/./node_modules/framer-motion/dist/es/components/AnimatePresence/PopChild.mjs:13:1)
    at PopChild (webpack-internal:///(ssr)/./node_modules/framer-motion/dist/es/components/AnimatePresence/PopChild.mjs:33:21)
    at PresenceChild (webpack-internal:///(ssr)/./node_modules/framer-motion/dist/es/components/AnimatePresence/PresenceChild.mjs:15:26)
    at AnimatePresence (webpack-internal:///(ssr)/./node_modules/framer-motion/dist/es/components/AnimatePresence/index.mjs:72:28)
    at PageTransitionEffect (webpack-internal:///(ssr)/./src/components/PageTransitionEffect/index.tsx:49:33)
    at div
    at div
    at body
    at html
    at RootLayout (webpack-internal:///(ssr)/./src/app/layout.tsx:21:23)
    at Lazy
    at RedirectErrorBoundary (webpack-internal:///(ssr)/./node_modules/next/dist/client/components/redirect-boundary.js:71:9)
    at RedirectBoundary (webpack-internal:///(ssr)/./node_modules/next/dist/client/components/redirect-boundary.js:79:11)
    at ReactDevOverlay (webpack-internal:///(ssr)/./node_modules/next/dist/client/components/react-dev-overlay/internal/ReactDevOverlay.js:66:9)
    at HotReload (webpack-internal:///(ssr)/./node_modules/next/dist/client/components/react-dev-overlay/hot-reloader-client.js:298:11)
    at Router (webpack-internal:///(ssr)/./node_modules/next/dist/client/components/app-router.js:154:11)
    at ErrorBoundaryHandler (webpack-internal:///(ssr)/./node_modules/next/dist/client/components/error-boundary.js:99:9)
    at ErrorBoundary (webpack-internal:///(ssr)/./node_modules/next/dist/client/components/error-boundary.js:128:11)
    at AppRouter (webpack-internal:///(ssr)/./node_modules/next/dist/client/components/app-router.js:426:13)
    at Lazy
    at Lazy
    at C:\Projects\node_modules\next\dist\compiled\next-server\app-page.runtime.dev.js:35:374733
    at C:\Projects\node_modules\next\dist\compiled\next-server\app-page.runtime.dev.js:35:374733
    at ServerInsertedHTMLProvider (C:\Projects\node_modules\next\dist\compiled\next-server\app-page.runtime.dev.js:38:23140)

The component code:

"use client";

import { motion, AnimatePresence } from "framer-motion";
import { usePathname } from "next/navigation";
import { LayoutRouterContext } from "next/dist/shared/lib/app-router-context.shared-runtime";
import { useContext, useRef } from "react";

function FrozenRouter(props: { children: React.ReactNode }) {
  const context = useContext(LayoutRouterContext);
  const frozen = useRef(context).current;

  return (
    <LayoutRouterContext.Provider value={frozen}>
      {props.children}
    </LayoutRouterContext.Provider>
  );
}

const variants = {
  hidden: { opacity: 0, x: -30, y: 0 },
  enter: { opacity: 1, x: 0, y: 0 },
  exit: { opacity: 0, x: -30, y: 0 },
};

const PageTransitionEffect = ({ children }: { children: React.ReactNode }) => {
  // The `key` is tied to the url using the `usePathname` hook.
  const key = usePathname();

  return (
    <AnimatePresence mode="popLayout">
      <motion.div
        key={key}
        initial="hidden"
        animate="enter"
        exit="exit"
        variants={variants}
        transition={{ type: "linear", duration: 0.2, delay: 0.1 }}
      >
        <FrozenRouter>{children}</FrozenRouter>
      </motion.div>
    </AnimatePresence>
  );
};

export default PageTransitionEffect;

2 Answers 2

18

Edit: As Adriano mentioned in his answer, you can easily implement an enter animation for your routes with the template.tsx file convention in Next JS. This does not, however, perform an exit animation for route changes. The solution I outline below does. I've updated my example to show both solutions.


There is currently a bug caused by the app router and shared layouts that prevents this from working correctly. However, there is a workaround. Besides the workaround, there are 3 other things we need:

  1. AnimatePresence from framer motion (This helps us use exiting and entering animations)
  2. A key on the motion element to trigger a re-render (This triggers the animation when the page changes)
  3. Add mode='popLayout' to AnimatePresence (This removes the old page from the tree immediately. You can play around with the mode value, different modes are better for some animations.)

Example:

"use client";

import { motion, AnimatePresence } from "framer-motion";
import { usePathname } from "next/navigation";
import { LayoutRouterContext } from "next/dist/shared/lib/app- router-context.shared-runtime";
import { useContext, useRef } from "react";

function FrozenRouter(props: { children: React.ReactNode }) {
  const context = useContext(LayoutRouterContext ?? {});
  const frozen = useRef(context).current;

  return (
    <LayoutRouterContext.Provider value={frozen}>
      {props.children}
    </LayoutRouterContext.Provider>
  );
}

const variants = {
  hidden: { opacity: 0, x: -200, y: 100 },
  enter: { opacity: 1, x: 0, y: 0 },
  exit: { opacity: 0, x: 0, y: -100 },
};

const PageTransitionEffect = ({ children }: { children: React.ReactNode }) => {
  // The `key` is tied to the url using the `usePathname` hook.
  const key = usePathname();

  return (
    <AnimatePresence mode="popLayout">
      <motion.div
        key={key}
        initial="hidden"
        animate="enter"
        exit="exit"
        variants={variants}
        transition={{ type: "linear" }}
        className="overflow-hidden"
      >
        <FrozenRouter>{children}</FrozenRouter>
      </motion.div>
    </AnimatePresence>
  );
};

export default PageTransitionEffect;

Here is a working example.

8
  • That's working now! Thanks a milion! Is there any downside when doing it? Commented Dec 6, 2023 at 1:20
  • Although it's working, there's a warning message on console (only happens when refreshing the page, not while changing the routes on client side) ... please see edit #1 Commented Dec 6, 2023 at 1:37
  • Hmmm, after playing around with it for a bit, I got this error: Cannot read properties of null (reading 'useContext'). It may need a refactor. I'll take a look and edit when I can.
    – Rico
    Commented Dec 6, 2023 at 3:52
  • @AlexandrePaiva I made a slight update to the code in the workaround. The thing about workarounds is they aren't guaranteed. We can do our best though 😅.
    – Rico
    Commented Dec 7, 2023 at 20:46
  • 1
    I've been messing around with the codesandbox example I posted in my answer. I'm unable to replicate the error that you're seeing though. I've been reading about that error you're seeing and attempting to fix it, but it's tricky without being able to replicate it.
    – Rico
    Commented Dec 12, 2023 at 20:55
1

There's a better approach for framer motion page transitions on Next.js 14, and for this case, the solution would be using its new template.js file, which is explained here under "File conventions" from Nextjs doc (must read).

So, after installing framer-motion we can create our page transition template file:

/app/template.tsx

"use client";

import { motion } from "framer-motion";

export default function Template({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <motion.div
      initial={{ y: 20, opacity: 0 }}
      animate={{ y: 0, opacity: 1 }}
      transition={{ ease: "easeInOut", duration: 0.75 }}
    >
      {children}
    </motion.div>
  );
}

Simply place it under /app/ root directory and the page transition will work for all your routes!

In case you want to set a different page transition for a specific route, duplicate the template file, change the transition animation as you like and place it within your specific route directory, for example: /app/dashboard, that way all routes within /app/dashboard/* will use your new transition!

Note that we're explicit defining 'use client' in template.tsx and that changes nothing about the way your root or page layout is going to render server or client components.

If we use /app/layout.js and place a page transition component there instead of using template.js, it would load the page transition animation during the first render (initial load) only. Because of how Next.js sets its caching strategy for layout.js file, if you were to navigate to other pages, Next.js would not re-render those pages from the layout, and page transition animation would not render for that page.

So, for that case template.tsx comes as a handy solution as it creates a new instance for each of their children when navigation changes.

here's a video explaining how this solution works: https://youtu.be/eUvzrCDc9FE?si=DvKSm35y4MjrYDnI

3
  • It should be the correct answer, worked as expected without errors, thank you
    – Ah Hu
    Commented Apr 25 at 11:32
  • Hey @AhHu I'm glad to know it helped you! I also prefer the template.tsx approach as it doesn't force you to stick to a single page transition. As a Client Component, one could enhance the template.js file with custom props or get params with the useSearchParams hook and decide which transition to use depending on a specific route. Also for every and each App Route or Group Routes you could use a differente template file with a complete different transition to handle a specific layout structure. Commented Apr 25 at 23:35
  • 2
    This is a great solution for a simple enter animation for each route, but it doesn't perform exit animations when the route is unmounted. I've updated my answer's example to show both of our solutions.
    – Rico
    Commented Apr 26 at 18:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.