Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[NEXT-1151] App router issue with Framer Motion shared layout animations #49279

Open
1 task done
maurocolella opened this issue May 5, 2023 · 135 comments
Open
1 task done
Labels
area: app App directory (appDir: true) bug Issue was opened via the bug report template. linear: next Confirmed issue that is tracked by the Next.js team.

Comments

@maurocolella
Copy link

maurocolella commented May 5, 2023

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
      Platform: linux
      Arch: x64
      Version: #22 SMP Tue Jan 10 18:39:00 UTC 2023
    Binaries:
      Node: 16.17.0
      npm: 8.15.0
      Yarn: 1.22.19
      pnpm: 7.1.0
    Relevant packages:
      next: 13.4.1-canary.1
      eslint-config-next: 13.0.7
      react: 18.2.0
      react-dom: 18.2.0

Which area(s) of Next.js are affected? (leave empty if unsure)

App directory (appDir: true)

Link to the code that reproduces this issue

https://codesandbox.io/p/sandbox/stupefied-browser-tlwo8y?file=%2FREADME.md

To Reproduce

I provided a larger repro for context, as it is unclear which combination of factors leads to the specific bug, although a number of other people report the same issue.

Describe the Bug

Framer Motion supports a feature called shared layout animation that automatically transitions components whose styles have changed when the container (that contains them) re-renders.

This feature appears not to be working in multiple scenarios with Next.js 13 under the app folder.

In the provided example, this feature is applied to the blue navigation highlight.

The affected container in the code sandbox is:
https://codesandbox.io/p/sandbox/stupefied-browser-tlwo8y?file=%2Flib%2Fcomponents%2FNavigation.tsx

To produce the undesired behavior, I simply applied layoutId as specified in the relevant Framer Motion documentation to the motion elements expected to transition.

Framer Motion 5 removes the AnimateSharedLayout component.
Now, you can use the layoutId prop and components will animate from one to another without the need for the AnimateSharedLayout wrapper.

I believe I also tried more explicit variations. Others have reported similar or identical issues in the bug currently open with Framer Motion.

Expected Behavior

I expect the blue highlight to slide smoothly to its new position when the nav container re-renders.

Which browser are you using? (if relevant)

Version 113.0.5672.63 (Official Build) (64-bit)

How are you deploying your application? (if relevant)

Usually Vercel

NEXT-1151

@maurocolella maurocolella added the bug Issue was opened via the bug report template. label May 5, 2023
@github-actions github-actions bot added the area: app App directory (appDir: true) label May 5, 2023
@joshdavenport
Copy link

joshdavenport commented May 5, 2023

As an extra point for this issue, the docs specify that using templates is a way to achieve enter/exit animations (web archive link, see edit) with either CSS or an animation library (for which framer-motion would be one of the go-to choices for most I feel) but doesn't offer any indication as to how to achieve this.

With templates, even if you wrap children in layout (where templates is rendered, and even given a key) transitions just don't work because there's no way to make that template a framer motion element with animate props.

Edit: This wording is now removed, just linking the docs as they were at this moment in time so it doesn't look like I was saying the docs say something it doesn't: web archive link

@zackdotcomputer
Copy link
Contributor

I believe I've pinpointed the issue that is causing this problem. As part of the new app router structure, Next lays out a tree of components that includes the following loop (rendering a hypothetical /path/subpath request):

- Root Layout
  - OuterLayoutRouter
    - TemplateContext.Provider key="path"
      - Root Template
        - InnerLayoutRouter
          - Path Layout
            - OuterLayoutRouter
              - TemplateContext.Provider key="subpath"
                - Path Template (not subpath, as that is a page.tsx)
                  - InnerLayoutRouter
                    - OuterLayoutRouter
                      - TemplateContext.Provider key="__PAGE__"
                        - Page contents

Crucially, the app framework is inserting an OuterLayoutRouter component between each Layout and corresponding Template. This component is what is responsible for performing the content swap when the user navigates to a new path. The system seems to select the lowest OuterLayoutRouter that can be used (e.g. for the path navigation /sign-up/step1 to /sign-up/step2 the second OuterLayoutRouter, which represents the directory /sign-up and lives inside any layout.tsx for that directory, would be used. If the paths were /sign-up/step/1 to /sign-up/step/2, then the third OuterLayoutRouter would be used. And so on...).

Because the OuterLayoutRouter fully swaps its contents to the new path, and because those contents include the template.tsx, the template cannot provide an "on exit" effect (as it will have been pruned from the tree already). Because the OuterLayoutRouter itself does not have a key (because it is not swapped), the layout cannot include an AnimatePresence because that component requires its direct child have a key that indicates navigation. Finally, because the usePathname function only updates after the render swap has been performed, one cannot sneak a key into the stack. If one tries to hack in an exit-enter effect by making a layout that uses the pathname to indicate when its child has changed, then the contents will be swapped to the new page and then fade-out and fade-back-in.

The potential fixes I see for this issue are:

  1. Next's render stack could be changed so that the Layout and Template are rendered in an immediate parent/child relationship, which TBH is what the documentation says should happen (I'll open a separate bug for this)
  2. Next could expose an API or event that indicates when a navigation begins and what the destination path is, so that one could add a key to the layout when loading begins.

I don't think there is a way with the APIs currently exposed to solve this issue on Framer's side without at least some change from Next.

@jamesvclements
Copy link

Just adding a +1 for this to be looked at soon, there's a lot of conversation about this in the Next.js discord as well

@alainkaiser
Copy link
Contributor

Would also love if you guys could have a look at it soon. A good amount of information already present in the framer-motion thread:

motiondivision/motion#1850

@timneutkens timneutkens added the linear: next Confirmed issue that is tracked by the Next.js team. label May 11, 2023
@timneutkens timneutkens changed the title App router issue with Framer Motion shared layout animations [NEXT-1151] App router issue with Framer Motion shared layout animations May 11, 2023
@timneutkens
Copy link
Member

timneutkens commented May 24, 2023

@seantai @jamesvclements @alainkaiser Please do not ping the thread with comments that do not add value. The issue is already synced into our tracker, there's hundreds of issues to be investigated and spamming issues demanding for it to be looked at is not the way to get us to look into it any faster, on the contrary, by posting these comments you're actively taking time away from us investigating / fixing issues. If all you want to do is "increase priority" you can use the 👍 on the initial post (not this post) to convey that you're running into it too.

Or you can focus your efforts on investigating / providing context on what might be causing the issue like the great comment @zackdotcomputer added.

@lmatteis
Copy link

lmatteis commented Jun 13, 2023

Wouldn't an easier approach simply be to let us choose where to put the key in the tree? Then we can have more fine grained control over when things are re-mounted.

As an example right now two different pages that return the same component in the same position will get remounted:

// app/foo/page.js
export default function Page() {
  return <Counter />;
}

// app/bar/page.js
export default function Page() {
  return <Counter />;
}

These two counter's state will be lost when soft-navigating between /foo and /bar.

By removing the key props from the tree that Next builds, we can decide ourselves if we want to remount things:

// app/foo/page.js
export default function Page() {
  const pathname = usePathname();
  return <Counter key={pathname} />; // <-- don't preserve the counter state on soft-navigations
}

This would of course allow us to properly adjust exit-animations, as well as other more fine-grained things we want to happen when soft-navigating.

@Piglow19
Copy link

Piglow19 commented Jul 9, 2023

Hello,
Any update ?

@harshv5094
Copy link

I have a question, I'm new to using nextjs framework. So It's my first time using an app router but I don't know how to use framer motion in app router.

@yawlad
Copy link

yawlad commented Jul 13, 2023

You can't correctly use framer motion for layout animations with app router for now

@Systemcluster
Copy link

You can't correctly use framer motion with app router for now

Apart from layout animations, Framer Motion works perfectly fine in client components.

@zackdotcomputer
Copy link
Contributor

Yeah to clarify, @harshv1741 - if you're looking to use Framer Motion to perform page transitions as the user navigates from page route to page route in app router, then that is what this issue is saying is broken. Because of how the NextJS team have structured their layouts feature, you can't do that right now.

If you're looking for how to use Framer Motion inside of page or specific component, then that is out of the scope of this thread to help you with - I'd suggest taking that over to Framer Motion's site and community.

@valenguerra
Copy link

Hi, is there any update? Or at least someone knows of another way to make an exit animation without using framer-motion?

@fweth
Copy link

fweth commented Jul 19, 2023

Hello, I just wanted to add that as far as I understand, Framer Motion as well as React Transition Group use React's cloneElement on children (or whatever you put in the ref). You can create a minimal page transition in a few lines of code for the old Next.js or Remix without any extra library, would be nice to have this support also for the App Router.

Here is how a simple exit-before-enter-animation looks like in vanilla Remix (and I'd expect it to work similarly with the App Router in the future):

export default function Layout() {
  const outlet = useOutlet();
  const [cloned, setCloned] = useState(outlet);
  const href = useHref();
  const mainRef = useRef();
  useEffect(
    function () {
      mainRef.current.style.opacity = 0;
      const timeout = window.setTimeout(function () {
        mainRef.current.style.opacity = 1;
        setCloned(cloneElement(outlet));
      }, 500);
      return function () {
        window.clearTimeout(timeout);
      };
    },
    [href],
  );
  return (
    <>
      <header>
        <nav>
          <Link to="/">Home</Link>
          <Link to="/news">News</Link>
          <Link to="/about">About</Link>
        </nav>
      </header>
      <main style={{ transition: "opacity 500ms" }} ref={mainRef}>
        {cloned}
      </main>
    </>
  );
}

@JasonA-work
Copy link

I agree with @fweth. Even in my app using the pages router, the only thing I'm using framer motion for is page transition animations. It'll be amazing if a solution and examples can be provided for simple page transition animation for both the pages and app router. A solution with vanilla css / js / react will help reduce a good amount of bundle size.

@ShahriarKh
Copy link
Contributor

For animating modals using parallel routes, since we use router.back() to close the modal (see nextgram example), we can set a timeout so we have enough time to render the exit animation before changing the route.

Inside the modal component:

'use client';

import css from './Modal.module.scss';
import { useCallback, useRef, useState } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { AnimatePresence, motion } from 'framer-motion';

export default function Modal() {
  const router = useRouter();
  const pathname = usePathname(); // to use pathname as motion key

  const [show, setShow] = useState(true); // to handle mounting/unmounting

  const onDismiss = useCallback(() => {
    setShow(false);
    setTimeout(() => {
      router.back();
    }, 200); // 200ms, same as transition duration (0.2)
  }, [router]);

  return (
    <AnimatePresence>
      {show && (
        <motion.div
          key={pathname}
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{
            duration: 0.2,
            ease: 'easeInOut',
          }}
        >
          {/* your modal content */}
        </motion.div>
      )}
    </AnimatePresence>
  );
}

To see the complete example of creating modals with parallel routes (albeit without animations), check out Nextgram

@cutsoy
Copy link

cutsoy commented Aug 11, 2023

The workaround I'm using memorizes the LayoutRouterContext (using useRef) and passes its down to its children. This ensures that the old route doesn't get unmounted on navigation.

Full example below:

/// layout.tsx
function FrozenRouter(props: PropsWithChildren<{}>) {
    const context = useContext(LayoutRouterContext);
    const frozen = useRef(context).current;

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

export default function Layout(props: PropsWithChildren<{}>) {
    const pathname = usePathname();
    
    return <AnimatePresence>
        <motion.div
            key={pathname}
            initial={{ opacity: 0 }}
            animate={{ opacity: 0 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.4, type: "tween" }}
        >
            <FrozenRouter>{props.children}</FrozenRouter>
        </motion.div>
    </AnimatePresence>;
}

This is working pretty good so far. Fingers crossed it works for you too! 🤞

@yaschet
Copy link

yaschet commented Aug 11, 2023

Hey, I appreciate your help. Can you add a Repo Link to the working code example or provide more information about the Context Provider Configuration?

@yaschet
Copy link

yaschet commented Aug 11, 2023

I just managed to piece it together. Here's how I implemented the solution:

import React, {useContext, useRef} from "react";
import { motion, AnimatePresence } from 'framer-motion';
import { PropsWithChildren, useRef } from 'react';
import { usePathname } from 'next/navigation'; // Import your pathname utility

import { LayoutRouterContext } from "next/dist/shared/lib/app-router-context";

function FrozenRouter(props: PropsWithChildren<{}>) {
  const context = useContext(LayoutRouterContext);
  const frozen = useRef(context).current;

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

export default function Layout(props: PropsWithChildren<{}>) {
  const pathname = usePathname();

  return (
    <AnimatePresence>
      <motion.div
        key={pathname}
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        transition={{ duration: 0.4, type: 'tween' }}
      >
        <FrozenRouter>{props.children}</FrozenRouter>
      </motion.div>
    </AnimatePresence>
  );
}

@cutsoy
Copy link

cutsoy commented Aug 11, 2023

Almost! The LayoutRouterContext is from next.js and seems to contain all of the routing state (hence why it needs to be frozen while animating the unmount of one of the routes). So you shouldn't define it yourself. Instead, just import it from next.

import { LayoutRouterContext } from "next/dist/shared/lib/app-router-context";

I will try to share an example of how to use it with nextgram tomorrow.

@lmatteis
Copy link

lmatteis commented Aug 12, 2023

Almost! The LayoutRouterContext is from next.js and seems to contain all of the routing state (hence why it needs to be frozen while animating the unmount of one of the routes). So you shouldn't define it yourself. Instead, just import it from next.

import { LayoutRouterContext } from "next/dist/shared/lib/app-router-context";

I will try to share an example of how to use it with nextgram tomorrow.

This actually works. Any reason why the API isn't public?

@leerob
Copy link
Member

leerob commented Aug 13, 2023

A few questions we'd love to hear more feedback on here:

  • Are you wanting to show a loading indicator like nprogress for every navigation?
    • Would you want to show this every time a Server Actions happens, as well? (a data mutation)
  • What would you want to happen when starting other React transitions?
    • e.g. If there's a Suspense boundary on the second page, should it stop when the loading state of the Suspense boundary is shown or when the last one completes?

@kylemh
Copy link
Contributor

kylemh commented Aug 14, 2023

Let me know if I'm way off base here, but this thread - I don't think - has anything to do with things like nProgress. It's more like transitioning within a layout between routes.

Easy to imagine with modal animations or fade-in and -out of previous to next route. Basically, all the example sites you see with the Chrome View Transitions API (but Framer Motion specifically)

Essentially, in the pages router, the AnimatePresence component worked flawlessly. Now, it's not viable and it seems much more difficult to do complex, staggered, or JS-heavy animations between routes of the same layout component.

@OKok-3
Copy link

OKok-3 commented Apr 28, 2024

[Note: I am very new to both next.js and framer] I've found another potentially very "hacky" way as a work around for exit animations on page redirect. I created a client component that monitors the browser URL (using usePathname), let's call it "Wrapper". It then simply returns the appropriate component based on the URL and acts as the "router". Any redirects then must be triggered with window.history.pushState and in page.tsx of every route you just return <Wrapper />. Doing this allowed me to make exit animations work. However, I feel like this kind of defeats the whole purpose of using next.js app router as there isn't any real redirects happening, and this is now essentially a single page application.

@fweth
Copy link

fweth commented Apr 30, 2024

I found another way to make page transitions work with the app router. It's a bit hacky, it uses the fact that useMemo runs before the HTML is updated, so inside useMemo I have the chance to clone the HTML node and then put it back after the router removed it:

"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { usePathname } from "next/navigation";

export default function Transition({ children }) {
  const [exiting, setExiting] = useState(false);
  const path = usePathname();
  const cloneRef = useRef();
  const innerRef = useRef();
  const outerRef = useRef();
  useMemo(
    function () {
      if (!innerRef.current) return;
      setExiting(true);
      cloneRef.current = innerRef.current;
    },
    [path]
  );
  useEffect(
    function () {
      if (exiting) {
        outerRef.current.appendChild(cloneRef.current);
        cloneRef.current.style.transition = "none";
        cloneRef.current.style.opacity = 1;
        window.setTimeout(function () {
          cloneRef.current.style.transition = "opacity 400ms";
          cloneRef.current.style.opacity = 0;
        }, 100);
        window.setTimeout(function () {
          setExiting(false);
          cloneRef.current.remove();
        }, 500);
        return () => cloneRef.current.remove();
      }
      window.setTimeout(function () {
        if (!innerRef.current) return;
        innerRef.current.style.opacity = 1;
      }, 100);
    },
    [exiting]
  );
  return (
    <div ref={outerRef}>
      {!exiting && (
        <div
          key={path}
          ref={innerRef}
          style={{ opacity: 0, transition: "opacity 400ms" }}
        >
          {children}
        </div>
      )}
    </div>
  );
}

@nadeemc
Copy link

nadeemc commented May 9, 2024

Was running into a similar issue with page router not updating motion.div in a way that would go from initial -> animate values. So, came up with this simple wrapper/workaround, for those looking for only a minimal entry animation like I was:

/* motion-div-reveal.tsx */
'use client';

import {DynamicAnimationOptions, HTMLMotionProps, useAnimate} from 'framer-motion';
import {PropsWithChildren, useEffect} from 'react';

export type MotionDivRevealProps = HTMLMotionProps<'div'>;

// This is a basic replacement for <motion.div> in scenarios where the app router is used to navigate
// between components that have an entry animation.
// This is a workaround for this issue:
// https://github.com/vercel/next.js/issues/49279
export const MotionDivReveal = (props: PropsWithChildren<MotionDivRevealProps>) => {
  const [scope, animate] = useAnimate();
  useEffect(() => {
    if (!scope.current) {
      return;
    }

    let containerKeyFrames: Record<string, any[]> = {};
    // Check if props.initial is a boolean type
    if (props.initial instanceof Object && props.animate instanceof Object) {
      // eslint-disable-next-line guard-for-in
      for (const key in props.initial) {
        // @ts-expect-error any type is inferred for this keys/values
        containerKeyFrames[key] = [props.initial[key], props.animate[key] ?? props.initial[key]];
      }
    } else {
      console.warn('MotionDivReveal: initial and/or animate prop is not an object, skipping animation.');
      return;
    }

    void animate(
      scope.current,
      containerKeyFrames,
      props.transition ?? {
        bounce: 0,
        duration: 0.3, /* 300ms */
      },
    );
  }, [/* no dependencies to ensure the animation only runs once, or is skipped if the scope is not set */]);

  return (
    <div ref={scope} className={props.className}>
      {props.children}
    </div>
  );
};

Then, this can be used like you would have used a <motion.div>, i.e.:

<MotionDivReveal 
    initial={{opacity: 0, x: -50}}
    animate={{opacity: 1, x: 0}}
>
    Watch me slide in
</MotionDivReveal>

This works because it fires the animations with a useEffect and useAnimate, so they always run on the client.

@by-huy
Copy link

by-huy commented May 16, 2024

I found a website which uses app router and has done page transitions with shared layout transitions. The transition also happens using browser back/forward.
https://www.lens.xyz/
Can someone tell me how?

Hey all, I built this website.

I used this method from this thread, but my LayoutRouterContext import was from a different path.

Here's the exact code for my frozen router.

import { PropsWithChildren, useContext, useRef } from "react";

import { LayoutRouterContext } from "next/dist/shared/lib/app-router-context.shared-runtime";

export function FrozenRouter(props: PropsWithChildren<{}>) {
  const context = useContext(LayoutRouterContext);
  const frozen = useRef(context).current;
  return (
    <LayoutRouterContext.Provider value={frozen}>
      {props.children}
    </LayoutRouterContext.Provider>
  );
}

Dependencies are [email protected] and [email protected]

Unsure if I can be any more helpful here, as this solution worked mostly fine for my use case, but I had to do some context provider magic for the persistent animation on the right-hand side of the website that is async from the main routes.

@lochie Just curious, have you had any issues with using the FrozenRouter method in production? Would love to use page transitions as apart of my client projects and personal projects but I'm afraid there might be drawbacks to using this method.

Fingers crossed that the Next.js team will be tackling this real soon, we all have been eagerly waiting for an official solution 🥹

@lochie
Copy link

lochie commented May 16, 2024

@lochie Just curious, have you had any issues with using the FrozenRouter method in production? Would love to use page transitions as apart of my client projects and personal projects but I'm afraid there might be drawbacks to using this method.

Fingers crossed that the Next.js team will be tackling this real soon, we all have been waiting eagerly for an official solution 🥹

@huyngxyz there are different issues for styling depending on what styling solution you use. i know we had issues with (s)css modules and had to implement an unmount delay for component styles, and styled-components also had some issues. tailwind might be okay 🤷‍♀️

there were definitely more issues than not, it was enough that i considered switching back to page router multiple times during development, and i still generally prefer to opt for page router when it comes to having animation-rich web apps depending if the app would benefit hugely from server components. it's all a balancing act.

@by-huy
Copy link

by-huy commented May 19, 2024

@lochie Awesome, thanks for sharing! Gonna give it a try and see how it's like with tailwind

@kaisarkuanysh
Copy link

is there any way to start exit animation when the data of next page started loading from server?

@mad-zephyr
Copy link

is there any news when this bug will be fixed in the app router? How to implement Exit without inventing wheels, will soon be two years old for this bug

@branbarh
Copy link

branbarh commented Aug 14, 2024

I was able to get exit transitions working thanks to #49279 (comment).

Couldn't figure out why they weren't working at first even after implementing the code from the above comment; turns out, you have to use Next.js's Link component rather than standard HTML <a> elements, or it won't work. Not sure why I wasn't using Link components to being with, but I figured I would leave this here in case someone else runs into the same issue.

@nuclei272
Copy link

t first even after implementing the code from

Yes it works that way or using router from next/navigation. Still, for intercepting modals, exit transitions don't work since the close button uses router.back() ... My work around was to save the previous path in a state management and then use it as the redirect path when the modal closes, but it's not a very good approach.

@nuclei272
Copy link

Yes it works that way or using router from next/navigation. Still, for intercepting modals, exit transitions don't work since the close button uses router.back() ... My work around was to save the previous path in a state management and then use it as the redirect path when the modal closes, but it's not a very good approach.

@Hartaithan
Copy link

I just managed to piece it together. Here's how I implemented the solution:

import React, {useContext, useRef} from "react";
import { motion, AnimatePresence } from 'framer-motion';
import { PropsWithChildren, useRef } from 'react';
import { usePathname } from 'next/navigation'; // Import your pathname utility

import { LayoutRouterContext } from "next/dist/shared/lib/app-router-context";

function FrozenRouter(props: PropsWithChildren<{}>) {
  const context = useContext(LayoutRouterContext);
  const frozen = useRef(context).current;

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

export default function Layout(props: PropsWithChildren<{}>) {
  const pathname = usePathname();

  return (
    <AnimatePresence>
      <motion.div
        key={pathname}
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        transition={{ duration: 0.4, type: 'tween' }}
      >
        <FrozenRouter>{props.children}</FrozenRouter>
      </motion.div>
    </AnimatePresence>
  );
}

this solution works for me
but has anyone found a way to remove this warning when refreshing the page?

Warning: Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported.
    at FrozenRouter (webpack-internal:///(ssr)/./components/frozen-router.tsx:14:25)
    at main
    at MotionComponent (webpack-internal:///(ssr)/./node_modules/framer-motion/dist/es/motion/index.mjs:49:65)
    at PresenceChild (webpack-internal:///(ssr)/./node_modules/framer-motion/dist/es/components/AnimatePresence/PresenceChild.mjs:16:26)
    at AnimatePresence (webpack-internal:///(ssr)/./node_modules/framer-motion/dist/es/components/AnimatePresence/index.mjs:53:32)
    at LayoutTransition (webpack-internal:///(ssr)/./components/layout-transition.tsx:31:13)
    at Lazy
    at body
    at html

warning only appears when refreshing, it doesn't appear when navigating through pages

@ferrianes
Copy link

ferrianes commented Nov 7, 2024

I just managed to piece it together. Here's how I implemented the solution:

import React, {useContext, useRef} from "react";
import { motion, AnimatePresence } from 'framer-motion';
import { PropsWithChildren, useRef } from 'react';
import { usePathname } from 'next/navigation'; // Import your pathname utility

import { LayoutRouterContext } from "next/dist/shared/lib/app-router-context";

function FrozenRouter(props: PropsWithChildren<{}>) {
  const context = useContext(LayoutRouterContext);
  const frozen = useRef(context).current;

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

export default function Layout(props: PropsWithChildren<{}>) {
  const pathname = usePathname();

  return (
    <AnimatePresence>
      <motion.div
        key={pathname}
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        transition={{ duration: 0.4, type: 'tween' }}
      >
        <FrozenRouter>{props.children}</FrozenRouter>
      </motion.div>
    </AnimatePresence>
  );
}

this solution works for me but has anyone found a way to remove this warning when refreshing the page?

Warning: Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported.
    at FrozenRouter (webpack-internal:///(ssr)/./components/frozen-router.tsx:14:25)
    at main
    at MotionComponent (webpack-internal:///(ssr)/./node_modules/framer-motion/dist/es/motion/index.mjs:49:65)
    at PresenceChild (webpack-internal:///(ssr)/./node_modules/framer-motion/dist/es/components/AnimatePresence/PresenceChild.mjs:16:26)
    at AnimatePresence (webpack-internal:///(ssr)/./node_modules/framer-motion/dist/es/components/AnimatePresence/index.mjs:53:32)
    at LayoutTransition (webpack-internal:///(ssr)/./components/layout-transition.tsx:31:13)
    at Lazy
    at body
    at html

warning only appears when refreshing, it doesn't appear when navigating through pages

try this frozen router

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

  if (!frozen) {
    return <>{props.children}</>;
  }

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

Reference

@feledori
Copy link

I personally feel that Next.js has forgotten a bit about people creating things other than huge apps. There is a community of creative developers using Next.js as well, not just app developers.

I believe I speak for most creative devs when I say it’s frustrating that the issue with router exit animations has been open for over two years. Being able to implement seamless exit animations is essential for creating great user experiences, but the current limitations force us into awkward workarounds.

Fixing this would be a huge relieve for the community.🙏

@joebentaylor1995
Copy link

joebentaylor1995 commented Nov 19, 2024

I left quite a large comment on the CEOs linkedin post months ago and he replied / reacted to EVERY comment other than mine.

Next do not care about its creative users, period.

@timmyomahony
Copy link

timmyomahony commented Nov 19, 2024 via email

@joshdavenport
Copy link

Not sure we would all agree app router is a total mess, there's a lot to love there for many of us and that really is the core source of our frustration - that we have this tool we love with a fundamental blocker. There can be no doubt though, they do not seem to care, or are avoiding this use case. The writing is on the wall given the lack of presence in this ticket despite its prominence.

I personally suspect there is something deep set architecturally in their view that makes supporting this too big of a change, and they'd rather leave us in limbo then rile us up by saying it simply wont happen.

@jazsouf
Copy link
Contributor

jazsouf commented Nov 20, 2024

I wonder if it's an RSC issue or just the way the router works. I bet the next.js is counting on View Transition API to solve this issue for them when it becomes available on Safari. But who knows when that will happen...

@feedthejim
Copy link
Contributor

Hi all, this is a long overdue response, but, as @jazsouf guessed, we've consulted with the React team on this particular issue. They advised us to wait for the built-in support for the View Transitions API in React, which they hope to tackle in the coming months.

@piotrski
Copy link

@jazsouf single-document view transitions (multi-document transitions are not supported yet but are relevant in frameworks like Astro) are supported on Safari 18, so the support is there. CSS view transitions work with Next.js Router, as demonstrated here: https://next-view-transitions.vercel.app/. The question is: if or when Motion plans to rewrite shared layout animations using the View Transition API?

@kylemh
Copy link
Contributor

kylemh commented Nov 22, 2024

hey @feedthejim correct me if I'm wrong, but - based off of what you just said - shouldn't this ticket then be marked as Closed; won't fix? It sounds like the plan is to support the View Transitions API via React instead of changing anything so that (formerly Framer-Motion) Motion's LayoutGroup or AnimatePresence will work properly in Layout components.

@paul-brumder
Copy link

Hey, just found out about this package : Next Transition Router, it looks promising but I'm curious if you have any comments to make about it?

@dikaio
Copy link
Contributor

dikaio commented Dec 18, 2024

Hey, just found out about this package : Next Transition Router, it looks promising but I'm curious if you have any comments to make about it?

very cool thank you!

@leerob
Copy link
Member

leerob commented Dec 31, 2024

Hey everyone, I wanted to share one solution that might be relevant for you all. Here was my use case:

  • I needed to animate between different routes, from / to an individual product page
  • The URL should update when changing routes, and both clicking back in the navbar and the browser back button need to work
  • Reloading the page on the product detail page /p/[slug] needs to correctly start on the detail state (no animation)

I can definitely empathize with this being confusing, and apologize we haven't done enough to create examples or show how this could be possible. For example, trying to animate across routes using framer-motion (now motion) using the default page files in the App Router won't work exactly – you can't use the layoutId to transition the element. You might think – okay, maybe I need to use intercepted routes for a modal-like pattern, but that also isn't the right solution here.

The solution I landed on is this:

  • I'm using motion to animate between my two different "states" in the app (grid of products, product detail page)
  • When clicking on a product, we start the animation but also shallow update the URL with window.history.pushState
  • We add a useEffect to listen to the popstate event to handle the browser back action
  • We have a /p/[slug]/page.tsx route, which has the detail page, to handle direct linking or reloads post-animation

This isn't perfect – for example, if you manually swipe back in iOS Safari. The most ideal solution here is View Transitions, which you can use https://next-view-transitions.vercel.app for in some cases. However, I couldn't get it working perfectly for the animation I was going for in this case, and also there isn't Firefox support yet for View Transitions. I do believe this is the best solution in the future though.

CleanShot.2024-12-29.at.14.56.21.mp4

Hope this helps! 🙏

@kylemh
Copy link
Contributor

kylemh commented Jan 1, 2025

Hey @leerob!

You said that you think View Transitions will be the best solution in the future. In the near term, did your experience adjust how you feel about this issue specifically? Will anything be done to improve the situation or is the sentiment still to wait for View Transitions? I'm just worried that we'll be waiting for quite awhile. Also, like you, I've sometimes had difficulty using View Transitions to get route-based transition animation done in a way that I have been able to do with motion,

@leerob
Copy link
Member

leerob commented Jan 1, 2025

Views Transitions could be the correct solution for some applications today. For example, I already use it on https://leerob.com, with progressive enhancement. However, like I mentioned if Firefox is key for your animation, that might be a hard requirement. I am sure it is possible to do the above animation with View Transitions (I saw the original creator of the site explored a version) I just didn't figure it out yet.

From a Next.js stance, we are still planning to align with View Transitions, so I don't expect a library change specifically for handling this case with framer-motion, especially with the other option/repo I included above with shallow routing. With that being said, things might change and will continue to keep tabs on this and related issues.

@leerob
Copy link
Member

leerob commented Jan 4, 2025

<ViewTransition> in React: facebook/react#31975

@bdrtsky
Copy link

bdrtsky commented Jan 4, 2025

<ViewTransition> in React: facebook/react#31975

Can't believe this is happening 🤞

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area: app App directory (appDir: true) bug Issue was opened via the bug report template. linear: next Confirmed issue that is tracked by the Next.js team.
Projects
None yet
Development

No branches or pull requests