Language: JavaScript
Animation
Framer Motion was created by the team behind Framer to provide a simple, yet powerful, way to animate React components. It leverages the power of the Framer library while being optimized for performance and accessibility, making complex animations achievable with minimal code.
Framer Motion is a production-ready motion library for React that allows developers to create animations and interactive UI transitions easily, using a declarative API.
npm install framer-motionyarn add framer-motionFramer Motion uses components like `<motion.div>` and hooks such as `useAnimation` to animate React elements. It supports animations for position, scale, rotation, opacity, and more, along with gestures, layout transitions, keyframes, and variants for complex animation sequences.
import { motion } from 'framer-motion';
function App() {
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 1 }}
>
Hello, Framer Motion!
</motion.div>
);
}Animates a div from opacity 0 to 1 over 1 second when the component mounts.
<motion.button whileHover={{ scale: 1.2 }}>
Hover me!
</motion.button>Scales the button up when hovered.
const boxVariants = {
hidden: { opacity: 0, x: -100 },
visible: { opacity: 1, x: 0 }
};
<motion.div initial='hidden' animate='visible' variants={boxVariants} transition={{ duration: 1 }} />Defines reusable animation states (variants) for a component and transitions between them.
<motion.div drag dragConstraints={{ left: 0, right: 100, top: 0, bottom: 100 }}>
Drag me!
</motion.div>Allows the user to drag the element within specified constraints.
<motion.div layout>
{items.map(item => (
<motion.div key={item.id} layout>{item.name}</motion.div>
))}
</motion.div>Animates the position of items automatically when the layout changes.
<motion.div animate={{ x: [0, 100, 50, 100, 0] }} transition={{ duration: 2 }} />Animates the element along multiple positions sequentially using keyframes.
Use variants to manage multiple animation states efficiently.
Prefer `layout` prop for automatic layout animations on reordering components.
Use `transition` properties to control timing and easing for smoother animations.
Leverage gesture props like `whileHover`, `whileTap`, and `drag` for interactive UIs.
Keep performance in mind: avoid animating large numbers of elements unnecessarily.