Component
Magnetic dock
A row of icons that swell toward your cursor and name themselves.
Usage
<MagneticDock
items={[
{ label: "Home", icon: "🏠", href: "/" },
{ label: "Work", icon: "📁", href: "/work" },
]}
/>Source
Copy both files into your project. The component has no dependencies beyond React.
"use client";
import { useRef, useState, type ReactNode } from "react";
import styles from "./magnetic-dock.module.css";
export type DockItem = { label: string; icon: ReactNode; href?: string; onClick?: () => void };
type MagneticDockProps = {
items: DockItem[];
/** Resting icon size in pixels. */
size?: number;
/** How much the icon under the cursor grows: 1.7 means 170%. */
magnify?: number;
/** How far the swell reaches either side, in pixels. */
reach?: number;
};
export function MagneticDock({ items, size = 44, magnify = 1.7, reach = 130 }: MagneticDockProps) {
const [pointer, setPointer] = useState<number | null>(null);
const [focused, setFocused] = useState<number | null>(null);
const refs = useRef<Array<HTMLElement | null>>([]);
function scaleFor(index: number) {
if (focused === index) return magnify;
const node = refs.current[index];
if (pointer === null || !node) return 1;
const rect = node.getBoundingClientRect();
const distance = Math.min(Math.abs(pointer - (rect.left + rect.width / 2)), reach);
// A cosine falloff: full size under the cursor, back to rest at the edge of the reach.
return 1 + (magnify - 1) * ((Math.cos((Math.PI * distance) / reach) + 1) / 2);
}
return (
<nav
className={styles.dock}
aria-label="Dock"
onPointerMove={(event) => event.pointerType === "mouse" && setPointer(event.clientX)}
onPointerLeave={() => setPointer(null)}
>
{items.map((item, index) => {
const px = size * scaleFor(index);
const body = (
<>
<span className={styles.icon} style={{ fontSize: px * 0.56 }}>
{item.icon}
</span>
<span className={styles.label}>{item.label}</span>
</>
);
const common = {
ref: (node: HTMLElement | null) => {
refs.current[index] = node;
},
className: styles.item,
style: { width: px, height: px },
"aria-label": item.label,
onFocus: () => setFocused(index),
onBlur: () => setFocused(null),
};
return item.href ? (
<a key={item.label} href={item.href} {...common}>
{body}
</a>
) : (
<button key={item.label} type="button" onClick={item.onClick} {...common}>
{body}
</button>
);
})}
</nav>
);
}