Magnetic Button
Wraps a button (or any element) with a magnetic pull effect. The element shifts toward the cursor on hover.
Use and inspectUse this when the motion supports the surrounding content. Connect callbacks and state to your app, keep the reset preview as a local demonstration, and add a reduced-motion fallback for movement or looping. The preview is synthetic; it does not call a backend.Next: inspect the source below and replace the demo inputs with your own data.
Magnetic ButtonWraps a button (or any element) with a magnetic pull effect. The element shifts toward the cursor on hover.
"use client";
import { useRef } from "react";
import type { MouseEvent } from "react";
type MagneticButtonProps = {
children: React.ReactNode;
strength?: number;
};
export function MagneticButton({ children, strength = 0.35 }: MagneticButtonProps) {
const ref = useRef<HTMLDivElement>(null);
function handleMouseMove(e: MouseEvent<HTMLDivElement>) {
const el = ref.current;
if (!el) return;
const rect = el.getBoundingClientRect();
const x = (e.clientX - (rect.left + rect.width / 2)) * strength;
const y = (e.clientY - (rect.top + rect.height / 2)) * strength;
el.style.transform = `translate(${x}px, ${y}px)`;
}
function handleMouseLeave() {
if (ref.current) {
ref.current.style.transform = "translate(0, 0)";
}
}
return (
<div
ref={ref}
style={{ display: "inline-flex", transition: "transform 0.2s cubic-bezier(0.25,0.46,0.45,0.94)" }}
onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave}
>
{children}
</div>
);
}Props
| Prop | Type | Default | Description |
|---|---|---|---|
| childrenrequired | ReactNode | — | Element to magnetize |
| strength | number | 0.35 | Magnetic pull factor (0–1) |