React + MotionButtons

Magnetic button

A button that drifts after your cursor on a spring and snaps back into place when you move away.

Settings

24px
0.5

Code

import { motion, useMotionValue, useSpring } from "framer-motion";

interface MagneticButtonProps {
  color?: string;
  radius?: number;
  text?: string;
  intensity?: number;
}

export default function MagneticButton({
  color = "#0071e3",
  radius = 24,
  text = "Hover me",
  intensity = 0.5,
}: MagneticButtonProps) {
  const x = useMotionValue(0);
  const y = useMotionValue(0);
  const sx = useSpring(x, { stiffness: 200, damping: 15 });
  const sy = useSpring(y, { stiffness: 200, damping: 15 });

  return (
    <motion.button
      type="button"
      style={{ x: sx, y: sy, backgroundColor: color, borderRadius: radius }}
      className="px-6 py-3 text-sm font-semibold text-white shadow-lg"
      onMouseMove={(e) => {
        const r = e.currentTarget.getBoundingClientRect();
        x.set((e.clientX - r.left - r.width / 2) * intensity);
        y.set((e.clientY - r.top - r.height / 2) * intensity);
      }}
      onMouseLeave={() => {
        x.set(0);
        y.set(0);
      }}
    >
      {text}
    </motion.button>
  );
}

Prompt for AI

Paste it into ChatGPT, Claude or Cursor and it will adapt the block to your project with these settings, even if you don’t use React.

More in Buttons

Where to use it

Use it on the one click that matters most: “Start free trial” on a SaaS landing page, “Get a quote” on a studio site, or the download button of an app. The way it follows the pointer draws the eye without flashing or shouting. If you were looking for a magnetic hover effect in React, this is it.

Start with the default intensity and only push it for large, isolated buttons. Next to a row of links it can feel restless. Touch screens have no hover, so on mobile it acts like a regular button.