Magnetic Element

Motion

Playful Tailwind magnetic element and Tailwind CSS interactive button components featuring cursor-attracting spring physics.

Add a delightful layer of interactivity to your interface with a Tailwind magnetic element. Perfect for primary calls to action, these Tailwind CSS interactive button wrappers use advanced spring physics to pull elements gently toward the user's cursor as they hover near, creating a tangible sense of mass and magnetism.

Magnetic elements work wonderfully when wrapping a standard Button or combined with a Social Share icon group for added flair.

Implementation

"use client";

import React, { useRef, useState } from "react";
import { motion } from "framer-motion";

interface MagneticProps {
  children: React.ReactNode;
  className?: string;
  strength?: number;
}

export const Magnetic: React.FC<MagneticProps> = ({
  children, className = "", strength = 0.3,
}) => {
  const ref = useRef<HTMLDivElement>(null);
  const [position, setPosition] = useState({ x: 0, y: 0 });

  const handleMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
    if (!ref.current) return;
    const rect = ref.current.getBoundingClientRect();
    const centerX = rect.left + rect.width / 2;
    const centerY = rect.top + rect.height / 2;
    setPosition({
      x: (e.clientX - centerX) * strength,
      y: (e.clientY - centerY) * strength,
    });
  };

  return (
    <motion.div ref={ref}
      onMouseMove={handleMouseMove}
      onMouseLeave={() => setPosition({ x: 0, y: 0 })}
      animate={{ x: position.x, y: position.y }}
      transition={{ type: "spring", stiffness: 150, damping: 15, mass: 0.1 }}
      className={className}>
      {children}
    </motion.div>
  );
};

Usage

Magnetic Buttons

<Magnetic strength={0.3}>
  <button>Hover me</button>
</Magnetic>
<Magnetic strength={0.5}>
  <div className="rounded-full"></div>
</Magnetic>

Strong Pull

Strong pull →

Higher strength value

<Magnetic strength={0.6}>
  <Card>Strong pull →</Card>
</Magnetic>

Props

PropTypeDefaultDescription
childrenReactNodeContent to make magnetic
classNamestring""Additional CSS classes
strengthnumber0.3Attraction intensity (0–1)