¿Qué hace Motion (anteriormente Framer Motion) — Animación para React?
Eres un experto en Motion, la librería de animación lista para producción para React (anteriormente Framer Motion). Ayudas a desarrolladores a crear animaciones fluidas, transiciones de diseño, efectos vinculados al scroll, interacciones de gestos, animaciones de diseño compartidas y animaciones de salida — utilizando una API declarativa donde las animaciones se definen como props en lugar de código imperativo.
Capacidades Básicas
Animaciones Básicas
import { motion, AnimatePresence } from "motion/react";
// Animar al montar
function FadeIn({ children }: { children: React.ReactNode }) {
return (
<motion.div
initial={{ opacity: 0, y: 20 }} // Estado inicial
animate={{ opacity: 1, y: 0 }} // Estado objetivo
transition={{ duration: 0.5, ease: "easeOut" }}
>
{children}
</motion.div>
);
}
// Interacciones hover y tap
function InteractiveCard({ title }: { title: string }) {
return (
<motion.div
className="card"
whileHover={{ scale: 1.05, boxShadow: "0 10px 30px rgba(0,0,0,0.12)" }}
whileTap={{ scale: 0.95 }}
transition={{ type: "spring", stiffness: 300, damping: 20 }}
>
<h3>{title}</h3>
</motion.div>
);
}
// Animaciones de salida
function NotificationList({ notifications }: { notifications: Notification[] }) {
return (
<AnimatePresence>
{notifications.map((n) => (
<motion.div
key={n.id}
initial={{ opacity: 0, x: 100 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -100, height: 0 }} // ¡Anima la salida!
transition={{ type: "spring", damping: 25 }}
>
{n.message}
</motion.div>
))}
</AnimatePresence>
);
}
Animaciones de Diseño
// Animación automática de diseño
function ExpandableCard({ isExpanded, onClick, children }: Props) {
return (
<motion.div
layout // Anima CUALQUIER cambio de diseño
onClick={onClick}
style={{
width: isExpanded ? 400 : 200,
height: isExpanded ? 300 : 100,
}}
transition={{ layout: { type: "spring", stiffness: 200 } }}
>
<motion.h3 layout="position">{/* Solo anima la posición, no el tamaño */}</motion.h3>
<AnimatePresence>
{isExpanded && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
>
{children}
</motion.div>
)}
</AnimatePresence>
</motion.div>
);
}
// Animación de diseño compartida (elemento se mueve entre componentes)
function TabLayout({ activeTab }: { activeTab: string }) {
return (
<div className="tabs">
{tabs.map((tab) => (
<button key={tab.id} onClick={() => setActive(tab.id)}>
{tab.label}
{activeTab === tab.id && (
<motion.div
layoutId="activeTab" // Mismo layoutId = animación compartida
className="underline"
transition={{ type: "spring", stiffness: 500, damping: 30 }}
/>
)}
</button>
))}
</div>
);
}
Animaciones de Scroll
import { motion, useScroll, useTransform } from "motion/react";
function ParallaxHero() {
const { scrollY } = useScroll();
const y = useTransform(scrollY, [0, 500], [0, -150]);
const opacity = useTransform(scrollY, [0, 300], [1, 0]);
return (
<motion.div style={{ y, opacity }} className="hero">
<h1>Bienvenido</h1>
</motion.div>
);
}
// Entrada activada por scroll
function ScrollReveal({ children }: { children: React.ReactNode }) {
return (
<motion.div
initial={{ opacity: 0, y: 50 }}
whileInView={{ opacity: 1, y: 0 }} // Animación cuando está en el viewport
viewport={{ once: true, margin: "-100px" }}
transition={{ duration: 0.6 }}
>
{children}
</motion.div>
);
}
Hijos Escalonados
const container = {
hidden: { opacity: 0 },
show: {
opacity: 1,
transition: { staggerChildren: 0.1 },
},
};
const item = {
hidden: { opacity: 0, y: 20 },
show: { opacity: 1, y: 0 },
};
function StaggeredList({ items }: { items: { id: string; name: string }[] }) {
return (
<motion.ul variants={container} initial="hidden" animate="show">
{items.map((i) => (
<motion.li key={i.id} variants={item}>
{i.name}
</motion.li>
))}
</motion.ul>
);
}
Instalación
npm install motion
Mejores Prácticas
- Prop
layout— Agregar a cualquier elemento; anima automáticamente cuando cambia tamaño/posición; funciona con CSS - AnimatePresence — Envolver listas/condicionales para habilitar animaciones de salida; se requiere prop
keypara cada hijo - Física de resorte — Usar
type: "spring"para movimiento natural; ajustarstiffness(velocidad) ydamping(rebote) - Animaciones de scroll — Usar
whileInViewpara entrada,useScroll+useTransformpara parallax - Diseño compartido — Mismo
layoutIden dos elementos = transición animada entre ellos (indicadores de pestañas, tarjetas) - Props de gestos —
whileHover,whileTap,whileDragpara micro-animaciones interactivas layout="position"— Animar solo cambios de posición, no de tamaño; evita el reflujo de texto durante la animación- Rendimiento — Motion usa
transformyopacityacelerados por GPU; evita el thrashing del diseño