Magnetic Cursor Effect

An interactive React component that adds a dynamic bubble effect, visually tracking cursor movement in real time.

1
// @ts-nocheck
2
'use client';
3
4
import React, { useRef, useEffect, useState } from 'react';
5
import { motion, useMotionValue, useSpring } from 'framer-motion';
6
7
const MagneticCursor: React.FC = () => {
8
const buttonRef = useRef<HTMLButtonElement | null>(null);
9
const x = useMotionValue(0);
10
const y = useMotionValue(0);
11
const springX = useSpring(x, { stiffness: 200, damping: 20 });
12
const springY = useSpring(y, { stiffness: 200, damping: 20 });
13
const [isHovering, setIsHovering] = useState(false);
14
15
useEffect(() => {
16
const handleMouseMove = (e: MouseEvent) => {
17
if (buttonRef.current) {
18
const button = buttonRef.current.getBoundingClientRect();
19
const centerX = button.left + button.width / 2;
20
const centerY = button.top + button.height / 2;
21
const deltaX = e.pageX - centerX;
22
const deltaY = e.pageY - centerY;
23
24
const distance = Math.sqrt(deltaX ** 2 + deltaY ** 2);
25
const magneticDistance = 120; // Distance for magnetic attraction
26
const attractionStrength = 0.45; // Magnetic strength
27
28
if (distance < magneticDistance) {
29
const strength = 1 - distance / magneticDistance;
30
x.set(deltaX * strength * attractionStrength);
31
y.set(deltaY * strength * attractionStrength);
32
setIsHovering(true);
33
} else {
34
x.set(0);
35
y.set(0);
36
setIsHovering(false);
37
}
38
}
39
};
40
41
window.addEventListener('mousemove', handleMouseMove);
42
43
return () => {
44
window.removeEventListener('mousemove', handleMouseMove);
45
};
46
}, [x, y]);
47
48
return (
49
<div className='relative w-full h-full flex items-center justify-center'>
50
<motion.button
51
ref={buttonRef}
52
className={`px-6 py-3 rounded-lg text-white font-semibold transition-transform ${
53
isHovering ? 'bg-green-500' : 'bg-green-600'
54
}`}
55
style={{
56
x: springX,
57
y: springY,
58
}}
59
>
60
Hover on me!
61
</motion.button>
62
</div>
63
);
64
};
65
66
export default MagneticCursor;
67

Installtion

1
npm install framer-motion