Alex
Alex

Reputation: 1401

How to use AnimatePresence on page transitions, but not have it affect nested children

I am using Framer Motion in a Next.js site to create page transitions, as well as other animations on the page.

For page transitions, I am using AnimatePresence around the page content:

<AnimatePresence
  mode="wait"
  initial={false}
  onExitComplete={() => {
    window.scrollTo(0, 0);
    setLoaderVisible(false);
  }}
>
  {children}
</AnimatePresence>

My pages are then wrapped with motion.div:

<motion.div
  initial={{ opacity: 0 }}
  animate={{ opacity: 1 }}
  exit={{ opacity: 0 }}
  transition={{
    type: 'easeInOut',
    duration: 0.5
  }}
>
  {children}
</motion.div>

This works fine. However, the initial=false property on AnimatePresence is affecting every subsequent framer animation on my site pages.

How do I ensure AnimatePresence and its settings only apply to the specific motion.div that I want it to, and not other motion.divs nested within that? Thanks

Upvotes: 0

Views: 585

Answers (1)

Waleed Salama
Waleed Salama

Reputation: 41

This worked for me: Wrap the {children} in another AnimatePresence with initial = {true}. This will reset the "initial" suppression deeper in the tree, and everything inside the page will animate normally.

<AnimatePresence
  mode="wait"
  initial={false}
  onExitComplete={() => {
    window.scrollTo(0, 0);
    setLoaderVisible(false);
  }}
>
  <motion.div
    initial={{ opacity: 0 }}
    animate={{ opacity: 1 }}
    exit={{ opacity: 0 }}
    transition={{
      type: 'easeInOut',
      duration: 0.5
    }}
  >
    <AnimatePresence initial>
        {children}
    </AnimatePresence>
  </motion.div>
</AnimatePresence>

I found the answer on this github issue

Upvotes: 0

Related Questions