Skip to main content
Magnetic Pill CTA

Magnetic Pill CTA

Cursor-attracted spring pill button with momentum.

Motion
13/16
Move cursor inside stage

1. Install Dependencies

$npm install framer-motion lucide-react

2. Copy Component Code

components/ui/MagneticPill.tsx
1"use client";
2
3import React, { useRef } from "react";
4import {
5 motion,
6 useMotionValue,
7 useReducedMotion,
8 useSpring,
9} from "framer-motion";
10
11interface MagneticPillProps {
12 label?: string;
13 onClick?: () => void;
14}
15
16export function MagneticPill({
17 label = "Get Cosrim UI",
18 onClick,
19}: MagneticPillProps) {
20 const areaRef = useRef<HTMLDivElement>(null);
21 const rawX = useMotionValue(0);
22 const rawY = useMotionValue(0);
23 const springX = useSpring(rawX, { stiffness: 240, damping: 18 });
24 const springY = useSpring(rawY, { stiffness: 240, damping: 18 });
25 const prefersReducedMotion = useReducedMotion();
26
27 function handleMove(event: React.PointerEvent<HTMLDivElement>) {
28 if (prefersReducedMotion || !areaRef.current) return;
29 const rect = areaRef.current.getBoundingClientRect();
30 const cx = rect.left + rect.width / 2;
31 const cy = rect.top + rect.height / 2;
32 rawX.set(Math.max(-24, Math.min(24, (event.clientX - cx) * 0.2)));
33 rawY.set(Math.max(-18, Math.min(18, (event.clientY - cy) * 0.2)));
34 }
35
36 return (
37 <div
38 ref={areaRef}
39 onPointerMove={handleMove}
40 onPointerLeave={() => {
41 rawX.set(0);
42 rawY.set(0);
43 }}
44 className="flex h-48 w-full items-center justify-center"
45 >
46 <motion.button
47 type="button"
48 onClick={onClick}
49 style={prefersReducedMotion ? undefined : { x: springX, y: springY }}
50 whileTap={prefersReducedMotion ? undefined : { scale: 0.96 }}
51 className="inline-flex h-11 items-center rounded-full bg-black px-6 text-sm font-medium text-white shadow-sm dark:bg-white dark:text-black"
52 >
53 <span>{label}</span>
54 </motion.button>
55 </div>
56 );
57}

Usage Example

import { MagneticPill } from "@/components/ui/MagneticPill";
export default function HeroCta() {
return <MagneticPill label="Get Cosrim UI" />;
}

3. Props Reference

Magnetic Pill CTA props API reference
PropTypeDefaultDescription
labelstring"Get Cosrim UI"Text rendered inside the magnetic button.
onClick() => voidundefinedClick handler attached to the pill button.