Please use Desktop to view and interact with components
Microinteractions200msspring
Magnetic Button
Button that magnetically follows your cursor
buttonmagneticinteractiveshadcn
Useto navigate between components
Preview
This component requires shadcn/ui
This component uses shadcn/ui components. Make sure you have shadcn/ui set up in your project.
- Install shadcn/ui:
npx shadcn-ui@latest init - Install required components based on the imports in the code (e.g.,
npx shadcn-ui@latest add button) - Ensure your
tailwind.config.tsandglobals.cssare configured as per shadcn/ui documentation
Code
TypeScript + React
'use client'
import { motion, useMotionValue, useSpring } from 'framer-motion'
import { useRef } from 'react'
import { Button } from '@/components/ui/button'
export function MagneticButton() {
const ref = useRef<HTMLButtonElement>(null)
const x = useMotionValue(0)
const y = useMotionValue(0)
const springX = useSpring(x, { stiffness: 300, damping: 20 })
const springY = useSpring(y, { stiffness: 300, damping: 20 })
const handleMouseMove = (e: React.MouseEvent<HTMLButtonElement>) => {
if (!ref.current) return
const rect = ref.current.getBoundingClientRect()
const centerX = rect.left + rect.width / 2
const centerY = rect.top + rect.height / 2
x.set((e.clientX - centerX) * 0.3)
y.set((e.clientY - centerY) * 0.3)
}
const handleMouseLeave = () => {
x.set(0)
y.set(0)
}
return (
<motion.div style={{ x: springX, y: springY }}>
<Button
ref={ref}
onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave}
>
Magnetic Button
</Button>
</motion.div>
)
}
How to Use
- 1Install Framer Motion:
npm install framer-motion - 2Set up shadcn/ui: Install shadcn/ui components used in this code. Check the imports in the code above and install the required components (e.g.,
npx shadcn-ui@latest add button card) - 3Copy the code from above
- 4Paste it into your project and customize as needed
- 5Colors are customizable via Tailwind CSS classes. The default theme uses dark mode colors defined in your globals.css file