Magnetic
Makes any element lean toward the pointer and spring back.
$
pnpm dlx shadcn@latest add https://lodeui.com/r/magnetic.jsoncomponents/examples/magnetic-demo.tsx
"use client";
import { ArrowRight, Heart } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Magnetic } from "@/components/ui/magnetic";
export default function MagneticDemo() {
return (
<div className="flex flex-wrap items-center justify-center gap-6">
<Magnetic><Button size="lg">Get started <ArrowRight /></Button></Magnetic>
<Magnetic strength={0.6}><Button size="icon" variant="outline" aria-label="Favorite"><Heart /></Button></Magnetic>
</div>
);
}When to use
- A primary call to action on a landing page.
When not to use
- Forms and dense UI.
Installation
$
pnpm dlx shadcn@latest add https://lodeui.com/r/magnetic.json1Install the dependencies
npm install motion2Copy the source into your project
components/ui/magnetic.tsx"use client"; import * as React from "react"; import { motion, useMotionValue, useReducedMotion, useSpring } from "motion/react"; export interface MagneticProps { children: React.ReactNode; /** How far the element follows the pointer, 0–1. */ strength?: number; className?: string; } /** Wraps any element so it leans toward the pointer, then springs back. */ export function Magnetic({ children, strength = 0.35, className }: MagneticProps) { const reduce = useReducedMotion(); const x = useMotionValue(0); const y = useMotionValue(0); const sx = useSpring(x, { stiffness: 220, damping: 16, mass: 0.4 }); const sy = useSpring(y, { stiffness: 220, damping: 16, mass: 0.4 }); return ( <motion.span className={className} style={{ display: "inline-block", x: sx, y: sy }} onPointerMove={(e) => { if (reduce || e.pointerType !== "mouse") return; const r = e.currentTarget.getBoundingClientRect(); x.set((e.clientX - r.left - r.width / 2) * strength); y.set((e.clientY - r.top - r.height / 2) * strength); }} onPointerLeave={() => { x.set(0); y.set(0); }} > {children} </motion.span> ); }
Usage
Import it from @/components/ui/magnetic after installing.
example.tsx
import { Magnetic } from "@/components/ui/magnetic";
import { Button } from "@/components/ui/button";
export function Cta() {
return <Magnetic><Button size="lg">Start free</Button></Magnetic>;
}API reference
Magnetic
Leans its child toward the pointer, then springs back.
| Prop | Type | Default | Description |
|---|---|---|---|
| strength | number | 0.35 | 0–1. |
Accessibility
- Off under reduced motion and for touch and pen input.
Motion
- Spring-follows the pointer; returns on leave.
Responsive behavior
- Mouse only.
Performance
- Motion values; no re-renders.
Notes for AI
- Use on one element per view.
This page as Markdown, for assistants and coding agents:
/components/magnetic/markdownThe full library index for assistants is at /llms.txt.
Lode222 doc pagesllms.txt