Current page fades while next page move in from multiple directions.
npm i framer-motion
import { BrowserRouter, Route, Routes, useLocation } from "react-router-dom";
import { AnimatePresence } from "framer-motion";
function App() {
const location = useLocation();
return (
<BrowserRouter>
<AnimatePresence initial={false}>
<Routes location={location} key={location.pathname}>
<Route path="/" element={<Home />} />
// more routes here
</Routes>
</AnimatePresence>
</BrowserRouter>
);
};
export default App;
components/PageTransition.tsx
import { motion, usePresence } from "framer-motion";
import { useEffect } from "react";
type PageProps = {
children: React.ReactNode;
};
type TVariants = {
initial: {
x: string;
};
animate: {
x: number;
};
exit: {
x: string;
opacity: number;
};
};
// values for right to left transition
const variants: TVariants = {
initial: {
x: "100vw",
},
animate: {
x: 0,
},
exit: {
x: "-100vw",
opacity: 0,
},
};
const PageTransition = ({ children }: PageProps) => {
const [isPresent, safeToRemove] = usePresence();
useEffect(() => {
!isPresent && setTimeout(safeToRemove, 1000);
}, [isPresent]);
return (
<motion.div
{...variants}
transition={{ duration: 0.5 }}
style={{ position: "absolute" }}
>
{children}
</motion.div>
);
};
export default PageTransition;
page/Home.tsx
const Home = () => {
return (
<PageTransition>
<div>Home</div>
</PageTransition>
);
};