← Components/Buttons

MagneticButton

magneticspring animationdark background
magnetic-button-v1.tsx
import { motion, useMotionValue, useSpring } from 'framer-motion';
import React from 'react';

interface MagneticButtonProps {
  children: React.ReactNode;
  className?: string;
}

const MagneticButton: React.FC<MagneticButtonProps> = ({ children, className }) => {
  const [reversed, setReversed] = React.useState(false);
  const x = useMotionValue(0);
  const y = useMotionValue(0);
  const springX = useSpring(x, { stiffness: 100, damping: 15 });
  const springY = useSpring(y, { stiffness: 100, damping: 15 });

  const handleMouseEnter = () => {
    setReversed(false);
  };

  const handleMouseMove = (e: React.MouseEvent<HTMLButtonElement>) => {
    const rect = (e.currentTarget as HTMLButtonElement).getBoundingClientRect();
    const mouseX = e.clientX - rect.left;
    const mouseY = e.clientY - rect.top;
    x.set(mouseX);
    y.set(mouseY);
  };

  return (
    <motion.button
      className={`${className} py-2 px-4 bg-[#C9A84C] text-[#0A0A0A] rounded-lg cursor-pointer`}
      onMouseEnter={handleMouseEnter}
      onMouseMove={handleMouseMove}
      style={{ x: springX, y: springY }}
    >
      {children}
    </motion.button>
  );
};

export default MagneticButton;

Component info

CategoryButtons
Frameworkreact
TierPREMIUM
Views5
Copies0

Dependencies

npm install framer-motion

About

A premium React button component that follows the cursor position with a smooth spring animation when hovered, adding a touch of magnetic attraction to your user interface. This animated button is perfect for dark-themed websites and applications, where the gold color provides a nice contrast. With its simple yet effective design, the MagneticButton is sure to enhance the user experience and make your website stand out. The button's magnetic effect is achieved using the framer-motion library, which provides a powerful and flexible way to animate React components. The MagneticButton component is customizable, allowing you to adjust the hover radius, spring animation, and other properties to fit your specific needs.

Pro component
Unlock this component and 17,500+ more with Empire UI Pro.
Get Pro →