React SwitchTransition in-out children preserve

28 views Asked by At

I'm trying to replicate the page transition of https://zajno.com/ with react-transition-group in NextJS 13 app router.

In my root layout I have this code:

export default function Shared({
  children
}: {
  children: React.ReactNode
}) {
  const pathname = usePathname()
  const ref = useRef(null),
    background = useRef(null);

  useEffect(() => {
    const ctx = gsap.context(() => {
      gsap.timeline({})
        .fromTo(ref.current, {
          clipPath: 'inset(90vh 10vh 10vh)',
        }, {
          clipPath: 'inset(0px 0px 0px)',
          duration: 1.2,
          delay: 1,
          ease: CustomEase.create("custom", "M0,0 C0.15,0.9 0.7,0.1 1,1"),
        })
        .to(background.current, {
          opacity: 0,
          duration: .7,
          ease: 'power4.inOut',
        }, '-=.2')

    });

    return () => ctx.revert();
  }, [pathname]);

  const [currentKey, setCurrentKey] = useState(pathname);

  useEffect(() => {
    setCurrentKey(pathname);
  }, [pathname]);


  return (
    <SwitchTransition mode="in-out">
        <Transition
            key={pathname}
            timeout={1200}
            unmountOnExit
        >
            {(state) => (
                <div className='absolute top-0 left-0 h-full w-full overflow-hidden'>
                    <div ref={ref} className={`absolute top-0 left-0 w-full h-full min-h-screen origin-top ${state}`}>
                        <div ref={background} className='bg-slate-800/[.8] fixed top-0 left-0 w-full h-full' />
                        <div className='absolute top-0 left-0 w-full'>
                            {children}
                        </div>
                    </div>
                </div>
            )}
        </Transition>
    </SwitchTransition>
)
}

Please find a working example here: https://codesandbox.io/p/sandbox/pensive-hawking-d744dx.

The transition works almost as expected, however, the "old" children are not preserved. It immediately renders the new children (clone) and the new children which animate. Is there a way to save the old children without updating their state?

0

There are 0 answers