Todos os componentes

Magnetic Hover Effect 02

Magnetic Hover Effect 02 é um componente de sobreposição para React e Tailwind CSS, da biblioteca Bund UI, com licença MIT. Copia e cola no teu projeto.

Bund UI MIT overlays

O que é

Magnetic Hover Effect 02 é um componente de sobreposição para React e Tailwind CSS, da biblioteca Bund UI, com licença MIT. Copia e cola no teu projeto.

Como usar

Abre o componente no catálogo, carrega em copiar, e cola no teu projeto. O prompt copiado leva o código e as regras para o teu agente o reproduzir sem alterar nada.

Abrir no catálogo

Cinco cópias grátis por mês. Sem cartão.

Precisa de

npm i motion

Licença

Este componente vem de Bund UI e é redistribuído sob a licença MIT, que permite uso comercial. O aviso de copyright viaja com o código.

Magnetic Hover Effect 02

examples/motion/animations/magnetic-hover-effect/02/magnetic-effect.tsx
"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;
examples/motion/animations/magnetic-hover-effect/02/page.tsx
import MagneticButton from "./magnetic-effect";
import { Button } from "@/components/ui/button";

export default function MagneticButtonExample() {
  return (
    <MagneticButton>
      <img
        className="aspect-square max-w-80 object-cover"
        src="/images/products/list3.png"
        alt="..."
      />
    </MagneticButton>
  );
}

Componentes parecidos