Search code examples
reactjsanimationnext.jsframer-motion

Framer Motion AnimatePresence Nested Import Problem


It would appear I've hit a peculiar problem with Framer Motion and it's exitBeforeEnter tag with regards to importing components that have the motion.div attribute.

The following works as intended:

<AnimatePresence exitBeforeEnter> 
<div>
    <CoverImageComp var={blah} var={blah}/>
    <AnimatePresence exitBeforeEnter>
      {!editing ? (
        <EditorComp key={router.pathname}/>
      :
        <PreviewComp key={router.pathname+'-preview'}/>
      )}
    </AnimatePresence>

</div>
</AnimatePresence>

However if I was to place the CoverImageComp into the !editing ternary operator than the exit animate breaks - with the whole page moving onto the next (via an onClick event)

    !editing ? (
        <>
         <CoverImageComp var={blah} var={blah}/>
         <EditorComp key={router.pathname}/>
        </>
    ): ...

The above doesn't appear to work, my first assumption was to add a unique key to the CoverImageComp much like router.pathname+'-cover'. I've also tried wrapping the editing blocks with a AnimatePresence which also didn't provide the desired outcome.

It's also worth nothing the imported components have the following motion tags attached to their container divs:

<motion.div
   variants={{
    initial: {
        x: '500px',
    },
    animate: {
        x: '0px',
    },
    exit: {
        x: '500px',
    },
    }}
    initial={'initial'}
    animate={'animate'}
    exit={'exit'}
    transition={{
        type: 'spring', mass: 0.35, stiffness: 45,
    }}
    className={styles.editor_form}
>

I am sure I'm following the directions laid out in Framer's API but I must be missing something!? Any help or guidance is greatly appreciated.


Solution

  • From

      !editing ? (
            <>
             <CoverImageComp var={blah} var={blah}/>
             <EditorComp key={router.pathname}/>
            </>
        ): ...
    

    To

      !editing ? (
            <React.Fragment key={router.pathname}>
             <CoverImageComp var={blah} var={blah}/>
             <EditorComp />
            </React.Fragment>
        ): ...
    

    I know it feels weird but the <> is sugar for or <React.Fragment /> depending on how you export. Like other components they need a key for framer to know if they change or not.

    https://reactjs.org/docs/fragments.html#keyed-fragments