Magnetic Hover Effect 01
Magnetic Hover Effect 01 is a React and Tailwind CSS overlay component from Bund UI, licensed MIT. Copy it and paste it into your project.
Bund UI
MIT
overlays
What it is
Magnetic Hover Effect 01 is a React and Tailwind CSS overlay component from Bund UI, licensed MIT. Copy it and paste it into your project.
How to use it
Open it in the catalogue, press copy, and paste it into your project. The prompt you copy carries the code and the rules that tell your agent to reproduce it without changing anything.
Five free copies a month. No card.
Needs
npm i motion
Licence
This component comes from Bund UI and is redistributed under the MIT licence, which permits commercial use. The copyright notice travels with the code.
Magnetic Hover Effect 01
"use client";
import React, { useState, useEffect, useRef } from "react";
import { motion, useMotionValue, useSpring } from "motion/react";
const SPRING_CONFIG = { damping: 100, stiffness: 400 };
type MagneticEffectType = {
children: React.ReactNode;
distance?: number;
};
function MagneticEffect({ children, distance = 0.6 }: MagneticEffectType) {
const [isHovered, setIsHovered] = useState(false);
const ref = useRef<HTMLDivElement>(null);
const x = useMotionValue(0);
const y = useMotionValue(0);
const springX = useSpring(x, SPRING_CONFIG);
const springY = useSpring(y, SPRING_CONFIG);
useEffect(() => {
const calculateDistance = (e: MouseEvent) => {
if (ref.current) {
const rect = ref.current.getBoundingClientRect();
const centerX = rect.left + rect.width / 2;
const centerY = rect.top + rect.height / 2;
const distanceX = e.clientX - centerX;
const distanceY = e.clientY - centerY;
if (isHovered) {
x.set(distanceX * distance);
y.set(distanceY * distance);
} else {
x.set(0);
y.set(0);
}
}
};
document.addEventListener("mousemove", calculateDistance);
return () => {
document.removeEventListener("mousemove", calculateDistance);
};
}, [ref, isHovered]);
return (
<motion.div
ref={ref}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
style={{
x: springX,
y: springY
}}>
{children}
</motion.div>
);
}
export default MagneticEffect;
import MagneticButton from "./magnetic-effect";
import { Button } from "@/components/ui/button";
export default function MagneticButtonExample() {
return (
<MagneticButton>
<Button size="lg">Don't leave me 😥</Button>
</MagneticButton>
);
}