Magnetic Icons

Interactive icons with magnetic hover effects.

Instagram icon
Apple icon
TikTok icon
Nox icon

Installation


Install dependencies

npm i framer-motion

Copy the CSS Markup

Copy The JSX Source Code

"components/magnetic-icons/magneticicons.jsx"
'use client'
import { useRef, useState } from 'react'
import { motion } from 'framer-motion';

export default function MagneticIcons({children}) {
    const ref = useRef(null);
    const [position, setPosition] = useState({x:0,y:0});

    const handleMouse = (e) => {
        const { clientX, clientY } = e;
        const {height, width, left, top} = ref.current.getBoundingClientRect();
        const middleX = clientX - (left + width/2)
        const middleY = clientY - (top + height/2)
        setPosition({x: middleX, y: middleY})
    }

    const reset = () => {
        setPosition({x:0, y:0})
    }

    const { x, y } = position;
    return (
        <motion.div
            style={{position: "relative"}}
            ref={ref}
            onMouseMove={handleMouse}
            onMouseLeave={reset}
            animate={{x, y}}
            transition={{type: "spring", stiffness: 150, damping: 15, mass: 0.1}}
        >
            {children}
        </motion.div>
    )
}