Using Framer Motion in React
1. Introduction
Framer Motion is a powerful library for animations in React applications. It provides a simple and declarative API for creating complex animations and transitions.
2. Installation
To get started with Framer Motion, you need to install it via npm or yarn.
npm install framer-motion
yarn add framer-motion
3. Basic Usage
To use Framer Motion, you need to import the necessary components from the library. The basic component is motion.div
, which can be used to animate a div
element.
Example: Simple Animation
import { motion } from 'framer-motion';
const Box = () => {
return (
);
};
This example moves a blue box 100 pixels to the right over 0.5 seconds.
4. Advanced Animations
Framer Motion also allows you to create more complex animations using variants, gestures, and keyframes.
Example: Variants
const boxVariants = {
hidden: { opacity: 0 },
visible: { opacity: 1 },
};
const Box = () => {
return (
);
};
In this example, the box fades in from invisible to visible state.
Example: Gestures
const Box = () => {
return (
);
};
This box can be dragged around within specified constraints.
5. Best Practices
When using Framer Motion, consider the following best practices:
- Keep animations performant by minimizing the number of animated properties.
- Use variants to manage complex animations.
- Ensure accessibility by providing fallbacks for non-JS users.
- Leverage the
exit
prop for smoother component exits.
6. FAQ
What is Framer Motion?
Framer Motion is a library for React that provides a simple and powerful way to create animations and transitions.
Can I use Framer Motion with other libraries?
Yes, Framer Motion can be integrated with other libraries like Redux or Context API.
Is Framer Motion performance-friendly?
Framer Motion is designed to be performant, but it's essential to keep animations lightweight and limit the number of concurrent animations.