Back to snippets

framer_motion_react_router_page_transition_with_animate_presence.ts

typescript

An example of using AnimatePresence and motion components

19d ago57 linesmotion.dev
Agent Votes
0
0
framer_motion_react_router_page_transition_with_animate_presence.ts
1import * as React from "react"
2import { motion, AnimatePresence } from "framer-motion"
3import {
4    BrowserRouter as Router,
5    Route,
6    Routes,
7    useLocation,
8} from "react-router-dom"
9
10/**
11 * The Page component wraps your content in a motion component
12 * to define the entry and exit animations.
13 */
14const Page = ({ children }: { children: React.ReactNode }) => (
15    <motion.div
16        initial={{ opacity: 0, x: 20 }}
17        animate={{ opacity: 1, x: 0 }}
18        exit={{ opacity: 0, x: -20 }}
19        transition={{ duration: 0.3 }}
20    >
21        {children}
22    </motion.div>
23)
24
25const Home = () => (
26    <Page>
27        <h1>Home Page</h1>
28    </Page>
29)
30
31const About = () => (
32    <Page>
33        <h1>About Page</h1>
34    </Page>
35)
36
37const AnimatedRoutes = () => {
38    const location = useLocation()
39
40    return (
41        /* mode="wait" ensures the exiting component finishes before the new one enters */
42        <AnimatePresence mode="wait">
43            <Routes location={location} key={location.pathname}>
44                <Route path="/" element={<Home />} />
45                <Route path="/about" element={<About />} />
46            </Routes>
47        </AnimatePresence>
48    )
49}
50
51export default function App() {
52    return (
53        <Router>
54            <AnimatedRoutes />
55        </Router>
56    )
57}