¿Qué hace Motion (Framer Motion) — Librería de Animaciones UI para React?
Animaciones declarativas para React. Muelles, gestos, animaciones de diseño y transiciones de página. Acelerado por GPU, listo para producción.
Descripción General
- Repositorio: github.com/motiondivision/motion (más de 26K estrellas)
- Lenguaje: TypeScript / React
- Licencia: MIT
- Instalación:
npm install motion - Documentación: motion.dev
- Nota: Framer Motion fue renombrado a Motion. Importa desde
motion/react.
API Principal
Animación Básica
import { motion } from "motion/react";
// Animar al montar
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
>
Hola Mundo
</motion.div>
// Animar al salir (requiere AnimatePresence)
import { AnimatePresence } from "motion/react";
<AnimatePresence>
{isVisible && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
>
Contenido
</motion.div>
)}
</AnimatePresence>
Física de Muelle (Spring)
<motion.div
animate={{ x: 100 }}
transition={{
type: "spring",
stiffness: 300,
damping: 20,
mass: 1,
}}
/>
// Preajustes
transition={{ type: "spring", bounce: 0.5 }} // 0 = sin rebote, 1 = muy rebotante
Variantes (Animaciones Orquestadas)
const container = {
hidden: { opacity: 0 },
show: {
opacity: 1,
transition: {
staggerChildren: 0.1, // Retardo entre hijos
delayChildren: 0.3, // Retardo inicial
},
},
};
const item = {
hidden: { opacity: 0, y: 20 },
show: { opacity: 1, y: 0 },
};
<motion.ul variants={container} initial="hidden" animate="show">
{items.map((i) => (
<motion.li key={i} variants={item}>{i}</motion.li>
))}
</motion.ul>
Gestos
// Hover
<motion.button
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
>
Haz clic
</motion.button>
// Arrastrar
<motion.div
drag // Habilitar arrastre en ambos ejes
dragConstraints={{ left: -100, right: 100, top: -50, bottom: 50 }}
dragElastic={0.2}
/>
Animaciones de Diseño (Layout)
// Animar automáticamente cambios de diseño
<motion.div layout>
{isExpanded ? <ContenidoExpandido /> : <ContenidoColapsado />}
</motion.div>
// Animación de diseño compartida (morfar entre elementos)
<motion.div layoutId="card">
{/* Este elemento morfa entre posiciones cuando layoutId coincide */}
</motion.div>
Animaciones de Desplazamiento (Scroll)
import { useScroll, useTransform, motion } from "motion/react";
function SeccionParallax() {
const { scrollYProgress } = useScroll();
const y = useTransform(scrollYProgress, [0, 1], [0, -200]);
const opacity = useTransform(scrollYProgress, [0, 0.5, 1], [1, 1, 0]);
return (
<motion.div style={{ y, opacity }}>
Contenido parallax
</motion.div>
);
}
useAnimate (Imperativo)
import { useAnimate } from "motion/react";
function MiComponente() {
const [scope, animate] = useAnimate();
async function handleClick() {
await animate(".box", { scale: 1.5 }, { duration: 0.3 });
await animate(".box", { rotate: 360 }, { duration: 0.5 });
await animate(".box", { scale: 1, rotate: 0 });
}
return (
<div ref={scope}>
<div className="box" onClick={handleClick}>Haz clic</div>
</div>
);
}
Fotogramas Clave (Keyframes)
<motion.div
animate={{
x: [0, 100, 100, 0, 0],
y: [0, 0, 100, 100, 0],
rotate: [0, 90, 180, 270, 360],
}}
transition={{ duration: 2, repeat: Infinity }}
/>
Tipos de Transición
// Spring (predeterminado para valores físicos)
transition={{ type: "spring", stiffness: 100, damping: 10 }}
// Tween (basado en duración)
transition={{ type: "tween", duration: 0.5, ease: "easeInOut" }}
// Opciones de easing
ease: "linear" | "easeIn" | "easeOut" | "easeInOut"
ease: [0.42, 0, 0.58, 1] // Cubic bezier personalizado
// Repetir
transition={{ repeat: Infinity, repeatType: "reverse", duration: 1 }}
// Retardo
transition={{ delay: 0.5 }}
Patrones Comunes
Transición de Página
// En el componente de layout
<AnimatePresence mode="wait">
<motion.div
key={pathname}
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -20 }}
transition={{ duration: 0.3 }}
>
{children}
</motion.div>
</AnimatePresence>
Lista Escalonada
const container = {
hidden: {},
show: { transition: { staggerChildren: 0.08 } },
};
const item = {
hidden: { opacity: 0, y: 15 },
show: { opacity: 1, y: 0, transition: { type: "spring", bounce: 0.3 } },
};
Tarjeta con Escala al Pasar el Ratón
<motion.div
whileHover={{ scale: 1.03, boxShadow: "0 10px 30px rgba(0,0,0,0.15)" }}
transition={{ type: "spring", stiffness: 400, damping: 25 }}
/>
Mejores Prácticas
- Usa variantes para animaciones orquestadas padre/hijo
- Física de muelle para movimiento natural (evita easing lineal)
- Propiedad layout para animaciones automáticas de cambio de diseño
- AnimatePresence requerido para animaciones de salida
- layoutId para transiciones de elementos compartidos entre rutas
- useScroll para animaciones vinculadas al desplazamiento (parallax, barras de progreso)
- whileHover/whileTap para retroalimentación interactiva
- Escalonar hijos mediante
transition.staggerChildrenen variantes - Mantén las animaciones sutiles — duración de 0.2-0.5s para interacciones UI
- Acelerado por GPU — Motion usa transformaciones por defecto
Cuándo Usar Motion vs GSAP
| Motion | GSAP | |
|---|---|---|
| Framework | React-first | Agnóstico de framework |
| Estilo | Declarativo (props JSX) | Imperativo (llamadas a funciones) |
| Animaciones de diseño | Integradas (mágicas) | Manual |
| Desplazamiento | Hook useScroll | Plugin ScrollTrigger |
| Gestos | Integrados (arrastrar, hover, tap) | Plugin Draggable |
| Morphing SVG | Limitado | Plugin MorphSVG |
| Tamaño del bundle | ~30KB | ~25KB núcleo |
Fuente
- Repositorio: github.com/motiondivision/motion
- Documentación: motion.dev
- Ejemplos: motion.dev/docs/react-quick-start