Botón Magnético
GratisBotones · Botón que se deja atraer por el cursor con un resorte suave; el texto se mueve con parallax.
Llevalo a tu proyecto
Pegá el código en tu proyecto, o pegá el prompt en Claude, Cursor, v0 o Lovable y que lo agregue por vos.
"use client";
import {
motion,
useReducedMotion,
useSpring,
useTransform,
type HTMLMotionProps,
} from "motion/react";
import { useRef, type PointerEvent, type ReactNode } from "react";
export type MagneticButtonProps = Omit<HTMLMotionProps<"button">, "children"> & {
children: ReactNode;
/** Cuánto sigue al cursor: 0 = nada, 1 = pegado. */
strength?: number;
};
const spring = { stiffness: 260, damping: 18, mass: 0.4 };
export function MagneticButton({
children,
strength = 0.35,
className = "",
onPointerMove,
onPointerLeave,
...props
}: MagneticButtonProps) {
const ref = useRef<HTMLButtonElement>(null);
const reduceMotion = useReducedMotion();
const x = useSpring(0, spring);
const y = useSpring(0, spring);
// El texto se mueve la mitad que el botón: da sensación de profundidad.
const labelX = useTransform(x, (value) => value * 0.5);
const labelY = useTransform(y, (value) => value * 0.5);
function handlePointerMove(event: PointerEvent<HTMLButtonElement>) {
onPointerMove?.(event);
const rect = ref.current?.getBoundingClientRect();
if (!rect || reduceMotion) return;
x.set((event.clientX - (rect.left + rect.width / 2)) * strength);
y.set((event.clientY - (rect.top + rect.height / 2)) * strength);
}
function handlePointerLeave(event: PointerEvent<HTMLButtonElement>) {
onPointerLeave?.(event);
x.set(0);
y.set(0);
}
return (
<motion.button
ref={ref}
style={{ x, y }}
whileTap={{ scale: 0.96 }}
onPointerMove={handlePointerMove}
onPointerLeave={handlePointerLeave}
className={`relative inline-flex items-center justify-center rounded-full bg-neutral-950 px-7 py-3 text-sm font-medium text-white shadow-lg shadow-black/20 outline-none focus-visible:ring-2 focus-visible:ring-neutral-400 focus-visible:ring-offset-2 dark:bg-white dark:text-neutral-950 ${className}`}
{...props}
>
<motion.span style={{ x: labelX, y: labelY }} className="inline-block">
{children}
</motion.span>
</motion.button>
);
}
Instalar con la CLI de shadcnAvanzado
Si tu proyecto ya usa shadcn, la CLI escribe el archivo y instala las dependencias sola.
npx shadcn@latest add @interfaz/boton-magnetico