Mastering Framer Motion: A Guide to Motion Components in React
Written on
Introduction to Framer Motion
Framer Motion is a powerful library that simplifies the process of adding animations to your React applications. This article provides a comprehensive guide on how to get started with motion components.
Understanding Motion Components
Motion components are specialized DOM elements designed to achieve smooth animations at 60 frames per second. For instance, if you want to create an animated div, you can utilize the motion.div component. Here’s an example of how to implement this:
import { motion } from "framer-motion";
import React from "react";
export default function App() {
return (
<>
<motion.div animate={{ rotate: 360 }} transition={{ duration: 2 }} /></>
);
}
In this snippet, the div will rotate 360 degrees over a period of 2 seconds.
Types of Supported Values
Framer Motion allows various types of values for animations, including:
- Numbers
- Strings
- Colors in hex, RGB, or HSL formats
- Complex strings comprising multiple numbers or colors
Instantaneous values will apply immediately, while values set within transitionEnd will take effect once the animation concludes.
Here’s how you can set different values:
import { motion } from "framer-motion";
import React from "react";
export default function App() {
return (
<>
<motion.div
animate={{
x: '100%',
backgroundColor: '#ff0000',
boxShadow: '0px 4px 10px rgba(0,0,0,0.5)',
position: 'fixed'
}}
transitionEnd={{ display: 'none' }}
/>
</>
);
}
In this example, various properties are animated, including position and color.
Value Type Conversion
Framer Motion can animate values of different types, specifically for dimensions and positions. For example:
import { motion } from "framer-motion";
import React from "react";
export default function App() {
return (
<>
<motion.div
initial={{ x: '100%' }}
animate={{ x: 'calc(100vw - 50%)' }}
/>
</>
);
}
Here, the initial and animated x values are of different types, yet Framer Motion handles the conversion seamlessly.
Utilizing Transform Properties
Transform properties leverage GPU acceleration, ensuring smooth animations. Common transform properties include:
- Translate: x, y, z or translateX, translateY, translateZ
- Scale: scale, scaleX, scaleY
- Rotate: rotate, rotateX, rotateY, rotateZ
- Skew: skew, skewX, skewY
- Perspective: transformPerspective
An example of using transform properties is as follows:
import { motion } from "framer-motion";
import React from "react";
export default function App() {
return (
<>
<motion.div
whileHover={{ scale: 1.1 }}/>
</>
);
}
By hovering over the div, you will observe smooth transitions in size.
Conclusion
Motion components provide an effective way to animate elements using Framer Motion, enhancing the user experience in your React applications.