Certainly! To implement page transitions in a React.js application using Framer Motion, you can follow these steps. I'll provide a simple example using Framer Motion's motion and AnimatePresence components for page transitions.
npm install framer-motion react-router-dom
Create a layout component that will handle the page transitions. Let's call it Layout.js:
// Layout.js
import React from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useLocation } from 'react-router-dom';
const Layout = ({ children }) => {
const location = useLocation();
return (
<AnimatePresence exitBeforeEnter>
<motion.div
key={location.pathname}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
>
{children}
</motion.div>
</AnimatePresence>
);
};
export default Layout;
In this component, we are using AnimatePresence to handle page transitions. The key attribute ensures that Framer Motion animates when the page changes.
Set up your main App.js file using React Router and the Layout component:
// App.js
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Layout from './Layout';
import Home from './Home'; // Create your Home component
import About from './About'; // Create your About component
const App = () => {
return (
<Router>
<Layout>
<Switch>
<Route path="/about" component={About} />
<Route path="/" component={Home} />
</Switch>
</Layout>
</Router>
);
};
export default App;
Replace Home and About with your actual page components.
Now, you can create your page components, such as Home.js and About.js. For example:
// Home.js
import React from 'react';
const Home = () => {
return (
<div>
<h1>Home Page</h1>
<p>Welcome to the home page!</p>
</div>
);
};
export default Home;
Now, when you navigate between the home and about pages, Framer Motion will handle the page transitions with a fade effect. Customize the animations and transitions based on your specific needs
Fade and scale transition:
// Layout.js
import React from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useLocation } from 'react-router-dom';
const Layout = ({ children }) => {
const location = useLocation();
return (
<AnimatePresence exitBeforeEnter>
<motion.div
key={location.pathname}
initial={{ opacity: 0, scale: 0.8 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.8 }}
transition={{ duration: 0.5 }}
>
{children}
</motion.div>
</AnimatePresence>
);
};
export default Layout;
Top comments (1)
AI generated/assisted posts - like this one - should try to adhere to the guidelines for such content.