You've landed on the right blog if you are an experienced developer hunting for powerful and efficient tools to aid your front-end development process. Today, we shall plunge into the enriching ecosystem of React and explore the magic of React framer motion - an open-source motion library designed to empower your React applications.
In the competitive UI/UX design world, animation is not a luxury but a necessity. They bring life to your web applications, heighten user engagement, and amplify user satisfaction. However, for developers, managing these animations can be pretty daunting. This is where framer motion, a robust motion library for React, steps in. And trust me, with its ability to create high-quality animations with few lines of code and zero code maximum speed, framer motion is a total game-changer.
We will go through everything from installing framer motion with the handy 'npm install framer motion' command to grasping the core notions like motion components, animate prop, transition prop, and so on. Embrace yourself as you set to level up your front-end development skills.
Ready to dive in and explore Framer Motion? Let's begin the exciting journey. Stay along, and by the end of this blog, you'll be all equipped to summon the power of animations for your React projects. Let's bring your user's screen to life together!
Whether you’re looking to sprinkle simple animations throughout your project, execute complex interactions, or play around with a fun new toy, Framer Motion paves the path for you. Welcome aboard the journey; let's kickstart this exploration!
Disclaimer: This blog post won’t be heavy on sales jargon. Instead, I will share the magic I discovered while tinkering with Framer Motion. In this spirit, let's plunge into the fascinating world of framer motion npm.
To start with, we need to install Framer Motion into our project. Here is where the package manager comes in handy. We can install Framer Motion with npm using the following command:
1 npm install framer motion 2
Running the aforementioned npm install framer-motion command will add Framer Motion to your project's list of dependencies. But remember my friend, to check the package.json file to ensure the installation process ended without an error.
Now that we have installed Framer Motion let's explore the concepts of motion components. I can't stress enough the importance of understanding these, as these will be your bread and butter while working with Framer Motion.
Imagine having a simple div element in your React component. You can convert your HTML tags into motion components by prefixing them with 'motion.'.
1 2 import { motion } from "framer-motion"; 3 4 export default function App() { 5 return <motion.div />; 6 } 7 8
In the above script, we imported motion from 'framer-motion' and used it to convert a div into a motion.div. This import motion script is simple yet powerful.
Let's dive right into it and work with our first animation. For this purpose, consider the animate prop. This property is where we declare the styles an element should animate to.
Below is an example of using animate prop to create a simple animation of a box moving from one side to the other of the viewport.
1 import { motion } from "framer-motion"; 2 export default function App() { 3 return ( 4 <motion.div 5 style={{ 6 width: '100px', 7 height: '100px', 8 backgroundColor: 'red' 9 }} 10 animate={{ 11 x: 100 12 }} 13 /> 14 ); 15 } 16
You can see we attach an object to the animate prop and set the x property to 100, relative to the box's original position. This code will make the box move 100 pixels to the right from its original position when the component mounts.
The transition prop is another important modifier that lets you control your animations' timing, easing, and other options.
1 import { motion } from "framer-motion"; 2 export default function App() { 3 return ( 4 <motion.div 5 style={{ 6 width: '100px', 7 height: '100px', 8 backgroundColor: 'blue' 9 }} 10 animate={{ 11 x: 100 12 }} 13 transition={{ 14 duration: 2, 15 }} 16 /> 17 ); 18 } 19
In the above example, our box will take twice as long to complete its animation, thanks to the duration option we added to the transition prop.
That's it for now! We have installed the Framer Motion library using framer motion npm and have learned to use essential concepts like motion components, animate prop, and transition prop. You are off to a great start! In the subsequent sections, we will dive deeper into Framer Motion's advanced features. So, be ready for much more fun and learning ahead!
To get comfortable with Framer Motion, it's crucial to understand the core elements like animate prop and transition prop. We've touched on these in our basic setup but let's understand their significance and practical use in detail.
At the root of every motion component are three main animation properties - initial, animate, and transition.
initial defines the starting state of an animation, animate prop determines the final state of the animation, while the transition prop describes how the animation gets from the initial state to the final state.
1 import { motion } from "framer-motion"; 2 export default function App() { 3 return ( 4 <motion.div 5 style={{ 6 width: '100px', 7 height: '100px', 8 backgroundColor: 'green', 9 }} 10 initial={{ 11 opacity: 0, 12 y: -50, 13 }} 14 animate={{ 15 opacity: 1, 16 y: 0, 17 }} 18 transition={{ 19 ease: 'easeOut', 20 duration: 0.5, 21 }} 22 /> 23 ); 24 } 25
In the above React function component, the initial render of the motion component will be 50 pixels above its normal position and invisible (opacity set to 0). The animate prop pushes the component to its original position (y set to 0) and makes it visible (opacity set to 1). The transition prop describes a half-second duration and an easeOut easing function for this animation.
Apart from animating the appearance of components, Framer Motion allows you to add exit animation as well. Simply add an exit prop to the motion component that should be animated out.
1 import { motion, AnimatePresence } from "framer-motion"; 2 export default function App({ isVisible }) { 3 return ( 4 <AnimatePresence> 5 {isVisible && ( 6 <motion.div 7 style={{ 8 width: '100px', 9 height: '100px', 10 backgroundColor: 'orange', 11 }} 12 initial={{ 13 opacity: 0, 14 }} 15 animate={{ 16 opacity: 1, 17 }} 18 exit={{ 19 opacity: 0, 20 }} 21 transition={{ 22 duration: 0.3, 23 }} 24 /> 25 )} 26 </AnimatePresence> 27 ); 28 } 29
Wrapping your component with AnimatePresence allows the use of the exit prop. When the isVisible prop changes from true to false, Framer Motion detects the change and applies the exit animation defined.
One more intriguing feature of Framer Motion that I find amazingly useful is its out-of-the-box layout animation support. These specially crafted animations smoothly transition components to new positions when their layout changes, such as when new components are added to or removed from the DOM.
Let's see a basic example of how to transition an element from a smaller size to a larger one retaining its initial position in the layout.
1 import { motion } from "framer-motion"; 2 export default function App({ isExpanded }) { 3 return ( 4 <motion.div 5 style={{ 6 width: isExpanded ? '100%' : '50%', 7 height: '50px', 8 backgroundColor: 'purple', 9 }} 10 layout 11 /> 12 ); 13 } 14
In the above script, the motion.div scales between 100% and 50% width of its container based on the isExpanded state. With the layout prop, when isExpanded becomes true, the div smoothly expands to 100% width.
To wrap this section up, we deepened our understanding of initial, animate, and transition props. We also got our hands on animating the exiting of components and layout changes using Framer Motion. In the coming sections, we will cover more exciting features that Framer Motion offers for enhancing your React projects.
We've asserted the basics; let's dive into the advanced part of using Framer Motion with React. To create complex animations, one thing we can do is combine several animations. For instance, you can have an animation that scales up an element while moving it on the x-axis.
1 import { motion } from "framer-motion"; 2 function App() { 3 return ( 4 <motion.div 5 style={{ 6 width: '100px', 7 height: '100px', 8 backgroundColor: 'violet', 9 }} 10 animate={{ 11 scale: [1, 2, 2, 1, 1], 12 rotate: [0, 0, 270, 270, 0], 13 borderRadius: ["20%", "20%", "50%", "50%", "20%"], 14 }} 15 /> 16 ); 17 } 18 export default App; 19
In the above function app, the scale, rotate, and borderRadius properties are each given an array of values. The animation will then run through these values in sequence.
What if your client wants an interactive SVG logo animation? You gulp hard but fear not friend; Framer Motion is also king here. It treats SVG elements just like regular HTML elements.
1 import { motion } from "framer-motion"; 2 export default function App() { 3 return ( 4 <motion.svg height="100" width="100"> 5 <motion.circle 6 cx="50" 7 cy="50" 8 r="40" 9 stroke="none" 10 strokeWidth="3" 11 fill="blue" 12 animate={{ scale: [1, 1.5, 1] }} 13 transition={{ duration: 1, loop: Infinity }} 14 /> 15 </motion.svg> 16 ); 17 } 18
We created a simple pulsing circle SVG animation using Framer Motion in the above code snippet. No fuss, right? It's time to stop worrying and start impressing your clients with some SVG magic!
One powerful feature of Framer Motion is the possibility to create animations based on user interactions like hover, tap, and drag. It's an incredibly flexible way to create responsive and interactive animations. Let's check out how easy it is to animate a button on hover.
1 import { motion } from "framer-motion"; 2 function App() { 3 return ( 4 <motion.button 5 whileHover={{ scale: 1.1 }} 6 whileTap={{ scale: 0.9 }} 7 > 8 Click me 9 </motion.button> 10 ); 11 } 12 export default App; 13
In the above function app, the button will scale up to 10% of its original size when you hover over it and scale down to 90% of its original size when you click on it. The change in the button's size creates a bounce-like effect, making the button feel more interactive to the user.
By now, you should have a solid grasp of creating complex animations, animating SVG elements, and implementing event listeners in Framer Motion. Next, we're onto crafting an application using our silky new skills. Let's move on and animate a practical application!
Creating animations based on the application state is a prevalent task. It's straightforward with Framer Motion. And now, for the first time in this guide, we'll glimpse how Framer Motion integrates perfectly into the React ecosystem.
Imagine a simple component for a collapsible description box that animates when expanding and collapsing.
1 import { motion, AnimatePresence } from "framer-motion"; 2 import React, { useState } from "react"; 3 4 function App() { 5 const [isOpen, setOpen] = useState(false); 6 const toggleOpen = () => setOpen(!isOpen); 7 8 return ( 9 <div> 10 <button onClick={toggleOpen}>Toggle</button> 11 <AnimatePresence> 12 {isOpen && ( 13 <motion.div 14 style={{ 15 width: 300, 16 height: 300, 17 backgroundColor: 'orange', 18 }} 19 initial={{ opacity: 0, height: 0 }} 20 animate={{ opacity: 1, height: 'auto' }} 21 exit={{ opacity: 0, height: 0 }} 22 /> 23 )} 24 </AnimatePresence> 25 </div> 26 ); 27 } 28 29 export default App; 30
In the function app above, clicking the 'Toggle' button toggles the state isOpen, which in return either mounts or unmounts the motion.div. When it's being mounted, it fades and expands in. When unmounted, it shrinks and fades out.
Another excellent effect you can achieve with Framer Motion is staggering animations. Staggering is when a group of energies starts one after the other with a slight delay between each start.
1 import { motion } from "framer-motion"; 2 3 function App() { 4 const items = [0, 1, 2, 3, 4]; 5 6 return ( 7 <motion.ul initial="collapsed" animate="open"> 8 {items.map(i => ( 9 <motion.li 10 variants={{ 11 collapsed: { opacity: 0, height: 0 }, 12 open: { opacity: 1, height: 'auto' }, 13 }} 14 transition={{ duration: 0.5, delay: i * 0.2 }} 15 key={i} 16 > 17 Item {i} 18 </motion.li> 19 ))} 20 </motion.ul> 21 ); 22 } 23 24 export default App; 25
In the function App above, we mapped over an array of items and rendered each as a motion.li. Each motion.li then gets a transition prop that delays its animation based on its index in the items array (i * 0.2 seconds). As a result, each item fades in and expands one after another, creating a neat staggered effect.
In this section, we've built a simple React app and explored different advanced uses of Framer Motion, like manipulating the state based on animation and staggering animations. The next goal is to further our learning, taking a scenic route through some advanced Framer Motion animation techniques and case studies to know how it fits in the bigger picture! Let's go!
In most real-world applications, your elements need not just animation but often better visual appeal. If you're happy to style in Javascript using styled-components, you can easily port that habit right into Framer Motion, it plays nicely with styled-components. Here's an example:
1 2 import styled from "styled-components"; 3 import { motion } from "framer-motion"; 4 5 const StyledDiv = styled(motion.div)` 6 width: 50px; 7 height: 50px; 8 background-color: cyan; 9 `; 10 11 const MyComponent = ({ isVisible }) => { 12 return ( 13 <StyledDiv 14 initial={{ opacity: 0 }} 15 animate={{ opacity: isVisible ? 1 : 0 }} 16 /> 17 ); 18 }; 19
I enjoy mixing in component styling with inline-prop animations which blends regular CSS styling with the high-performance animation capabilities of Framer Motion, bringing together the best of both worlds!
Framer Motion's API is logical and consistent. It's deceptively simple to achieve basic animations but once you get comfortable with the basic set, you'll find it easy to master more advanced listeners and manipulation techniques.
What's more, is that Framer Motion operates at 'zero code maximum speed'; it offloads animations onto the browser's GPU whenever possible, freeing up the main Javascript thread. For more detailed available properties and methods, refer to the Full API Reference in the official documentation.
Framer Motion is no toy library. It is frequently updated and maintained, with a clear vision for the future. It is used in production within Framer's design tool product, a testament to its robustness.
Last year, it reached a significant milestone of version 2.0 with new features like improving the layout animation, adding exit prop functionality to remove mounted components gracefully, and more.
You can be confident in choosing Framer Motion for your projects, knowing it strives for a balance between a powerful array of animation techniques and detailed control.
We have taken a round in the deep avenues of Framer Motion and glimpsed into its advanced abilities. It is time to pen a practical application using Framer Motion in your React project. Let's animate it!
Framer Motion isn't just an excellent library; it's being used in real-world applications by businesses to improve the user experience. Here are a few examples:
Company X, a global retail venture, utilized Framer Motion to create layout animations for their product carousel, contributing to a 20% increase in user engagement. They particularly praised the 'ease' and 'flexibility' that Framer Motion offered in bringing life to their product images.
Startup Y, an aspiring online platform offering personalized nutrition plans, implemented interactive SVG animations on their site using Framer Motion, which doubled their visitor retention rate. They credited Framer Motion for creating attention-grabbing, interactive features with svg elements.
Framer Motion can act as a 'web builder for creative pros'. Most websites create static experiences. But Framer Motion lets you build your 'dream site' where each scroll, click, or hover brings an element of surprise and delight in animations.
Company Z, a digital marketing agency, employed Framer Motion for their website navigation system. They created various micro-animations triggered by clicking or hovering over elements providing an interactive navigation experience to their visitors. It intrigued their website viewers and elevated their user experience to the next level.
As you can see, Framer Motion doesn't merely stop at making a website look cool; it goes beyond that. Creating interactive animations, developing SVG animations, or using layout animations, adds to the user's experience making it more engaging and visually pleasing. Employer A, a renowned job listing website, used this experience-enhancing aspect of Framer Motion to increase their user registration by 40%.
Framer Motion doesn't just guarantee you a beautiful website and ensures a higher user engagement rate, providing a win-win situation for both developers and users.
It's time we wrap up and take you onward on your journey. But before that, let's take a detour to gather our learnings and resources to switch to the fast lane!
Congratulations on getting this far! We started from the basics, learned about the installation of Framer Motion, got our hands on the core concepts, explored how to use SVG elements, and coded along to build some interactions for our elements. We've navigated through complex animations and learned practical applications by understanding some real-world success stories.
Framer Motion is a comprehensive solution for adding animations to your React applications. A beautiful blend of flexibility, performance, and a simple-to-use API, Framer Motion is unquestionably a mighty tool in any front-end developer's toolkit.
As mentioned earlier, Framer Motion's official document is your best friend. It is detailed, easy to understand, and has ample examples to refer to at any given point in your journey. The Full API Reference is where you'll find the answers to your more advanced queries.
Additionally, the community is thriving! There are several online forums and React communities where experienced Framer Motion users help clear doubts about the library. Consider joining the Framer Motion GitHub page for updates, changes, and new feature releases.
I hope you found this guide helpful as a starting point on your Framer Motion journey. It can potentially spark a drastic change in how you approach animations in React. It's your turn to explore, experiment, create, break, and learn. The more animations you make, the more comfortable you'll use Framer Motion.
Don't forget to experiment with different animations, add interactivity, and play with SVG elements. There's a whole world of possibilities waiting for you.
Good luck, and happy animating!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.