Motion: [BUG] In Next.js, Dynamic Imports (Custom Loading Components) is not exiting when using AnimatePresence's exitBeforeEnter

Created on 5 Dec 2019  路  4Comments  路  Source: framer/motion

I'm not sure if this is a bug or i'm doing it wrong but shouldn't the custom loading component trigger an exit?

// Page.js
const MyComponent = dynamic(() => import('MyComponent'), 
{
    loading : () => { 
        return <motion.div key="loader" initial={{ opacity: 0 }} animate={{ opacity : 1 }} exit={{ opacity : 0, x : 1000 }}>
                    <p>Loading...</p>
                </motion.div>
        },
        ssr : false
}
);

const Page = ()=>{
    function done(){
        alert("I should be called...") // does not get called
    }

    return <AnimatePresence exitBeforeEnter onExitComplete={done}>
        <MyComponent/>
    </AnimatePresence>

}

// MyComponent.js
export function MyComponent(){
    return <motion.div key="mycomponent" initial={{ opacity: 0 }} animate={{ opacity : 1 }} exit={{ opacity : 0, x : 1000 }}>Component</motion.div>
}
bug

Most helpful comment

Hello @cybervaldez , I think the Key (literally) is to set a key to the component:
<MyComponent key={...}/>

You can see it in this post:
https://reacttricks.com/animating-next-page-transitions-with-framer-motion/

If you are using dynamic routing the key={router.route} will not work, because the route is the same for the dynamic pages (e.g. /p/[id]). You can use the route.asPath or any other unique key here. I used the page ID. After I updated the key it worked for me. The components enter and exit as expected.

All 4 comments

I would like to try and fix this as my first contribution to motion. :)

I am experiencing the same issue with dynamic routes in Next.js. Are there any updates on this?

Without an easily reproducible example I'm going to have to close this. I would like to fix it, I suspect the fix lies within Next's dynamic implementation, but won't have the time to reproduce. CodeSandbox is acceptable or a GitHub repo.

Hello @cybervaldez , I think the Key (literally) is to set a key to the component:
<MyComponent key={...}/>

You can see it in this post:
https://reacttricks.com/animating-next-page-transitions-with-framer-motion/

If you are using dynamic routing the key={router.route} will not work, because the route is the same for the dynamic pages (e.g. /p/[id]). You can use the route.asPath or any other unique key here. I used the page ID. After I updated the key it worked for me. The components enter and exit as expected.

Was this page helpful?
0 / 5 - 0 ratings