The AnimatePresence component from the framer-motion library is used for animating components when they enter or exit the DOM. When used in conjunction with react-router-dom, it allows you to animate page transitions when navigating between routes.

To make the AnimatePresence exit prop work with react-router-dom, you need to ensure the following:

  1. Wrap the Routes with AnimatePresence: Wrap your <Routes> component (or <Switch> component, if you are using older versions of react-router-dom) with the AnimatePresence component. This allows AnimatePresence to detect when a route is exiting.

    For example:

    jsx
    import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; import { AnimatePresence, motion } from 'framer-motion'; const App = () => { return ( <Router> <AnimatePresence exitBeforeEnter> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> {/* Add more routes as needed */} </Routes> </AnimatePresence> </Router> ); };
  2. Use motion.div for Animated Components: For components that you want to animate when they enter or exit, wrap them with motion.div. This provides the animation properties needed by AnimatePresence to perform the transitions.

    For example:

    jsx
    import { motion } from 'framer-motion'; const Home = () => { return ( <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} > {/* Your Home component content */} </motion.div> ); };

    In this example, the Home component will fade in when it enters and fade out when it exits.

  3. Ensure Unique key for Animated Components: For AnimatePresence to detect when a component is exiting, each component wrapped with motion.div should have a unique key prop. This allows AnimatePresence to differentiate between different instances of the same component.

    For example:

    jsx
    import { motion } from 'framer-motion'; const Home = () => { return ( <motion.div key="home" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} > {/* Your Home component content */} </motion.div> ); };

    Make sure to provide a unique key prop for each component in your route configuration.

By following these steps, you should be able to use the AnimatePresence exit prop with react-router-dom to animate page transitions when navigating between routes. If you encounter any issues, ensure that you have the correct versions of framer-motion and react-router-dom and that you have correctly configured the animation properties for the components you want to animate.

Have questions or queries?
Get in Touch