Back to Component Explorer

Magnetic Button

buttons

Spatial button featuring smooth mouse offset tracking and fluid spring displacement.

#button#magnetic#spatial#interactive
Live Interactive Preview

Component Source Code

Select language in the dropdown
MagneticButton.tsx
1'use client';
2
3import React, { useState } from 'react';
4
5export default function MagneticButton() {
6 const [position, setPosition] = useState({ x: 0, y: 0 });
7
8 const handleMouseMove = (e: React.MouseEvent<HTMLButtonElement>) => {
9 const rect = e.currentTarget.getBoundingClientRect();
10 const x = (e.clientX - (rect.left + rect.width / 2)) * 0.35;
11 const y = (e.clientY - (rect.top + rect.height / 2)) * 0.35;
12 setPosition({ x, y });
13 };
14
15 const handleMouseLeave = () => {
16 setPosition({ x: 0, y: 0 });
17 };
18
19 return (
20 <button
21 onMouseMove={handleMouseMove}
22 onMouseLeave={handleMouseLeave}
23 style={{
24 transform: `translate3d(${position.x}px, ${position.y}px, 0px)`,
25 transition: position.x === 0 ? 'transform 0.5s ease-out' : 'transform 0.1s ease-out'
26 }}
27 className="relative rounded-full border border-blue-500/40 bg-blue-50/80 dark:bg-blue-950/40 px-6 sm:px-7 py-2.5 sm:py-3 text-sm font-semibold text-blue-600 dark:text-blue-400 shadow-sm hover:border-blue-500 hover:bg-blue-100/80 dark:hover:bg-blue-900/50 hover:shadow-blue-500/20 active:scale-95 transition-colors"
28 >
29 Magnetic Touch
30 </button>
31 );
32}

Installation & Integration Guide

Step 1: Tailwind CSS v4 Setup
Tailwind Docs

If you do not have Tailwind installed yet, run this installation command:

Terminal
npm install tailwindcss @tailwindcss/postcss postcss

Then add the Tailwind directive to your main stylesheet (globals.css):

@import "tailwindcss";

Step 2: Install Icon Dependencies

npm install lucide-react react-icons

Step 3: Add Component File

Create a new file in your project at src/components/buttons/MagneticButton.tsx and paste the copied code from the source viewer above.

Step 4: Usage Example

ExamplePage.tsx
1import MagneticButton from '@/components/buttons/MagneticButton';
2
3export default function ExamplePage() {
4 return (
5 <main className="p-8 flex items-center justify-center min-h-screen">
6 <MagneticButton />
7 </main>
8 );
9}