Lens
A magnifying glass effect for React: a round lens follows the cursor over an image, illustration or any content and shows a zoomed view inside it. Works with the mouse, with press-and-hold on touch screens and with the keyboard, and never re-renders React while it moves.
- Any content, not only images
- Keyboard & touch
- Motion values
- Zoom & size props
- prefers-reduced-motion
Hover, press and hold on touch, or Tab in and use the arrow keys.
import { Lens } from "@/components/dusk/lens/lens";
// A tiny deterministic generator, so the skyline is identical on the server and the client.
function lcg(seed: number) {
let s = seed;
return () => (s = (s * 1664525 + 1013904223) % 4294967296) / 4294967296;
}
const rand = lcg(2024);
const stars = Array.from({ length: 70 }, () => ({ x: rand() * 640, y: rand() * 170, r: 0.4 + rand() * 0.9 }));
let cursor = 0;
const buildings: { x: number; w: number; h: number }[] = [];
while (cursor < 640) {
const w = 34 + Math.floor(rand() * 46);
buildings.push({ x: cursor, w, h: 70 + Math.floor(rand() * 170) });
cursor += w + 4;
}
function Skyline() {
return (
<svg viewBox="0 0 640 320" className="block h-auto w-full" role="img" aria-label="A city skyline at night">
<defs>
<linearGradient id="lens-demo-sky" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stopColor="#020617" />
<stop offset="0.7" stopColor="#0f172a" />
<stop offset="1" stopColor="#1e293b" />
</linearGradient>
</defs>
<rect width="640" height="320" fill="url(#lens-demo-sky)" />
{stars.map((s, i) => (
<circle key={i} cx={s.x.toFixed(1)} cy={s.y.toFixed(1)} r={s.r.toFixed(2)} fill="#e2e8f0" opacity="0.8" />
))}
<circle cx="520" cy="62" r="26" fill="#f1f5f9" />
<circle cx="510" cy="56" r="26" fill="#020617" opacity="0.9" />
{buildings.map((b, i) => (
<g key={i}>
<rect x={b.x} y={320 - b.h} width={b.w} height={b.h} fill={i % 3 ? "#0b1220" : "#0d1a1f"} />
{Array.from({ length: Math.floor((b.h - 14) / 10) }, (_, row) =>
Array.from({ length: Math.floor((b.w - 6) / 7) }, (_, col) =>
(row * 7 + col * 3 + i) % 5 === 0 ? (
<rect
key={`${row}-${col}`}
x={b.x + 5 + col * 7}
y={320 - b.h + 8 + row * 10}
width="3"
height="4"
fill={(row + col + i) % 4 ? "#fde68a" : "#fef3c7"}
/>
) : null
)
)}
</g>
))}
<text x="12" y="310" fill="#94a3b8" fontSize="7" fontFamily="monospace">
N 52.3676° E 4.9041° · 02:14 local · 1,842 windows lit
</text>
</svg>
);
}
export default function LensDemo() {
return (
<div className="w-full max-w-xl">
<Lens className="border border-white/10">
<Skyline />
</Lens>
<p className="mt-3 text-center text-sm text-white/60">Hover, press and hold on touch, or Tab in and use the arrow keys.</p>
</div>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/lens.json1. Install the dependencies.
npm install motion2. Copy the source into
components/dusk/lens/lens.tsx.lens.tsx "use client"; import * as React from "react"; import { motion, useMotionTemplate, useMotionValue, useReducedMotion } from "motion/react"; import { cn } from "@/lib/utils"; export interface LensProps extends React.HTMLAttributes<HTMLDivElement> { /** The content to magnify: an image, an SVG, a block of text… */ children: React.ReactNode; /** Magnification inside the lens. */ zoom?: number; /** Diameter of the lens in px. */ size?: number; /** Optional sharper content for the lens (e.g. a high-resolution image), laid out exactly like `children`. */ lensContent?: React.ReactNode; /** Pixels the lens moves per arrow-key press (×4 with Shift). */ keyboardStep?: number; /** Milliseconds a finger must rest before the lens appears on touch screens. */ holdDelay?: number; /** Classes for the lens ring. */ lensClassName?: string; } /** * A round magnifier that follows the cursor over any content. Inside the lens * a second, `inert` copy of the content is scaled around the pointer and * clipped to a circle, all through motion values, so moving it never * re-renders React. * * Mouse and pen show it on hover. On touch, press and hold to bring it up, * then drag; the page doesn't scroll while it is open. With the keyboard, * focus the area to show it in the centre, move it with the arrow keys and * hide it with Escape. */ export function Lens({ children, zoom = 2, size = 170, lensContent, keyboardStep = 16, holdDelay = 220, lensClassName, className, onPointerMove, onPointerEnter, onPointerLeave, onPointerDown, onPointerUp, onPointerCancel, onFocus, onBlur, onKeyDown, onContextMenu, ...props }: LensProps) { const reduceMotion = useReducedMotion(); const rootRef = React.useRef<HTMLDivElement>(null); const [active, setActive] = React.useState(false); const activeRef = React.useRef(false); const hold = React.useRef<{ timer: number; x: number; y: number; id: number } | null>(null); const x = useMotionValue(0); const y = useMotionValue(0); const r = size / 2; const scale = Math.max(1, zoom); const clipPath = useMotionTemplate`circle(${r}px at ${x}px ${y}px)`; const origin = useMotionTemplate`${x}px ${y}px`; const ringX = useMotionTemplate`calc(${x}px - 50%)`; const ringY = useMotionTemplate`calc(${y}px - 50%)`; const show = React.useCallback((on: boolean) => { activeRef.current = on; setActive(on); }, []); const moveTo = React.useCallback( (px: number, py: number) => { const el = rootRef.current; if (!el) return; x.set(Math.min(Math.max(px, 0), el.clientWidth)); y.set(Math.min(Math.max(py, 0), el.clientHeight)); }, [x, y] ); const fromEvent = (event: React.PointerEvent<HTMLDivElement>) => { const rect = event.currentTarget.getBoundingClientRect(); return [event.clientX - rect.left, event.clientY - rect.top] as const; }; const cancelHold = () => { if (hold.current) window.clearTimeout(hold.current.timer); hold.current = null; }; // Touch: once the lens is up, stop the page from scrolling under the finger. // React's touch listeners are passive, so this needs a native one. React.useEffect(() => { const el = rootRef.current; if (!el) return; const block = (event: TouchEvent) => { if (activeRef.current) event.preventDefault(); }; el.addEventListener("touchmove", block, { passive: false }); return () => { el.removeEventListener("touchmove", block); if (hold.current) window.clearTimeout(hold.current.timer); }; }, []); return ( <div ref={rootRef} tabIndex={0} role="group" aria-roledescription="magnifier" aria-label={props["aria-label"] ?? "Magnifier. Use the arrow keys to move the lens, Escape to hide it."} data-slot="lens" data-active={active || undefined} className={cn( "relative isolate overflow-hidden rounded-xl outline-none [-webkit-touch-callout:none]", "focus-visible:ring-[3px] focus-visible:ring-ring/50", active && "cursor-none select-none", className )} onPointerEnter={(event) => { onPointerEnter?.(event); if (event.pointerType === "touch") return; moveTo(...fromEvent(event)); show(true); }} onPointerMove={(event) => { onPointerMove?.(event); const [px, py] = fromEvent(event); if (event.pointerType !== "touch") { moveTo(px, py); if (!activeRef.current) show(true); return; } if (activeRef.current) moveTo(px, py); else if (hold.current && Math.hypot(px - hold.current.x, py - hold.current.y) > 10) cancelHold(); }} onPointerLeave={(event) => { onPointerLeave?.(event); if (event.pointerType !== "touch") show(false); }} onPointerDown={(event) => { onPointerDown?.(event); if (event.pointerType !== "touch") return; const [px, py] = fromEvent(event); cancelHold(); hold.current = { x: px, y: py, id: event.pointerId, timer: window.setTimeout(() => { if (!hold.current) return; moveTo(hold.current.x, hold.current.y); show(true); }, holdDelay), }; }} onPointerUp={(event) => { onPointerUp?.(event); if (event.pointerType !== "touch") return; cancelHold(); show(false); }} onPointerCancel={(event) => { onPointerCancel?.(event); cancelHold(); if (event.pointerType === "touch") show(false); }} onContextMenu={(event) => { onContextMenu?.(event); // Long-press on touch opens the context menu on Android; the lens owns that gesture. if (activeRef.current || hold.current) event.preventDefault(); }} onFocus={(event) => { onFocus?.(event); if (event.target !== event.currentTarget || activeRef.current) return; // Only for keyboard focus; a mouse click already placed the lens. if (!event.currentTarget.matches(":focus-visible")) return; moveTo(event.currentTarget.clientWidth / 2, event.currentTarget.clientHeight / 2); show(true); }} onBlur={(event) => { onBlur?.(event); show(false); }} onKeyDown={(event) => { onKeyDown?.(event); if (event.defaultPrevented) return; const stepPx = keyboardStep * (event.shiftKey ? 4 : 1); const moves: Record<string, [number, number]> = { ArrowLeft: [-stepPx, 0], ArrowRight: [stepPx, 0], ArrowUp: [0, -stepPx], ArrowDown: [0, stepPx], }; const move = moves[event.key]; if (move) { event.preventDefault(); if (!activeRef.current) { moveTo(event.currentTarget.clientWidth / 2, event.currentTarget.clientHeight / 2); show(true); return; } moveTo(x.get() + move[0], y.get() + move[1]); } else if (event.key === "Escape" && activeRef.current) { event.preventDefault(); show(false); } else if ((event.key === "Enter" || event.key === " ") && !activeRef.current) { event.preventDefault(); moveTo(event.currentTarget.clientWidth / 2, event.currentTarget.clientHeight / 2); show(true); } }} {...props} > {children} <motion.div aria-hidden inert data-slot="lens-view" className="pointer-events-none absolute inset-0 z-10" style={{ clipPath, WebkitClipPath: clipPath }} initial={false} animate={{ opacity: active ? 1 : 0 }} transition={{ duration: reduceMotion ? 0 : 0.15 }} > <motion.div className="absolute inset-0" style={{ scale, transformOrigin: origin }}> {lensContent ?? children} </motion.div> </motion.div> <motion.div aria-hidden data-slot="lens-ring" className={cn( "pointer-events-none absolute left-0 top-0 z-20 rounded-full border border-white/30", "shadow-lg", lensClassName )} style={{ width: size, height: size, x: ringX, y: ringY }} initial={false} animate={{ opacity: active ? 1 : 0, scale: active || reduceMotion ? 1 : 0.96 }} transition={reduceMotion ? { duration: 0 } : { duration: 0.18, ease: "easeOut" }} /> </div> ); }
Usage
import Image from "next/image"
import { Lens } from "@/components/dusk/lens/lens"
export function ProductPhoto() {
return (
<Lens zoom={2.5} size={180} aria-label="Product photo magnifier">
<Image src="/sneaker.jpg" alt="Sneaker, side view" width={800} height={600} />
</Lens>
)
}Examples
Fine print
The lens magnifies any markup, including text. Here a smaller size and a higher zoom make tiny terms readable.
Pro plan
$12 / month
Billed annually at $144. Prices exclude local taxes. Cancel any time from your account settings and keep access until the end of the billing period. Seats beyond the first ten are charged pro rata on the next invoice. Usage over 100,000 requests per month is billed at $0.20 per additional 1,000 requests.
import { Lens } from "@/components/dusk/lens/lens";
export default function LensFinePrint() {
return (
<Lens zoom={2.6} size={140} className="w-full max-w-md border border-white/10 bg-card">
<div className="space-y-3 p-6">
<p className="text-sm font-medium text-muted-foreground">Pro plan</p>
<p className="text-3xl font-semibold text-foreground">
$12<span className="text-base font-normal text-white/50"> / month</span>
</p>
<p className="text-[9px] leading-snug text-white/55">
Billed annually at $144. Prices exclude local taxes. Cancel any time from your account settings and keep access
until the end of the billing period. Seats beyond the first ten are charged pro rata on the next invoice.
Usage over 100,000 requests per month is billed at $0.20 per additional 1,000 requests.
</p>
</div>
</Lens>
);
}Zoom & size
A 3.5× lens with a larger ring over a fine dot grid. Restyle the ring with lensClassName. For images, pass a higher-resolution copy as lensContent for a sharper view.
import { Lens } from "@/components/dusk/lens/lens";
export default function LensPattern() {
return (
<Lens
zoom={3.5}
size={220}
aria-label="Dot grid magnifier. Use the arrow keys to move the lens."
className="h-72 w-full max-w-xl border border-white/10"
>
<div
className="size-full bg-card"
style={{
backgroundImage: "radial-gradient(circle at 1px 1px, rgb(255 255 255 / 0.3) 0.6px, transparent 1px)",
backgroundSize: "8px 8px",
}}
/>
</Lens>
);
}API Reference
Put padding on the content rather than on Lens, so the magnified copy lines up exactly. Also accepts any div attribute; pass aria-label to describe what is being magnified.
| Prop | Type | Default | Description |
|---|---|---|---|
| children | ReactNode | — | The content to magnify. |
| zoom | number | 2 | Magnification inside the lens (minimum 1). |
| size | number | 170 | Lens diameter in px. |
| lensContent | ReactNode | — | Optional sharper content for the lens, laid out like children. |
| keyboardStep | number | 16 | Pixels per arrow-key press; ×4 with Shift. |
| holdDelay | number | 220 | Milliseconds a finger must rest before the lens appears on touch. |
| lensClassName | string | — | Classes for the lens ring. |
Accessibility
- The area is focusable. Keyboard focus shows the lens in the centre; the arrow keys move it (Shift for bigger steps), Enter or Space brings it back and Escape hides it.
- On touch screens, press and hold to show the lens, then drag; a quick swipe still scrolls the page as usual.
- The magnified copy is aria-hidden and inert, so screen readers and the Tab key only meet the original content once.
- Give the area an aria-label that says what is being magnified, and keep alt text on the image itself.
- With prefers-reduced-motion the lens appears and disappears without fading or scaling; it still follows the pointer directly.