Skip to content
Browse documentation

An image opens from its exact place in the grid, becomes a spacious viewer, and finds its way back.

Used forPortfolio and case studiesProduct screenshot galleriesListings and product photosTemplate and theme previews

Install with the shadcn CLI

$ npx shadcn@latest add @hairline/expanding-gallery

Older shadcn CLI, or a network that blocks ui.shadcn.com? Install by URL: shadcn add https://hairlineui.com/r/expanding-gallery.json. More

Templates

Need the whole page?

65 Next.js landing pages, each designed from scratch. Try any of them live; one is $39, all of them $159, and 8 are free.

Where it’s used

  • Portfolio and case studies

    Open a project from its thumbnail into a large viewer.

  • Product screenshot galleries

    Let visitors look closely at the interface on a landing page.

  • Listings and product photos

    Browse several photos of a property, a product or a venue.

  • Template and theme previews

    Show a set of designs that open at full size.

What it handles for you

A gallery that opens a lightbox from nowhere loses the sense of which image you picked. This opens each image from its own place in the grid and sends it back there.

Instead of wiring upa lightbox librarya modal dialogimage size measuringswipe handlingfocus trapping
  1. It opens from its thumbnail

    The image grows from its exact place in the grid into the viewer, keeping its proportions. The caption follows a moment later.

  2. It returns where it came from

    Closing sends the current image back to its own thumbnail, or fades it if the thumbnail has scrolled out of view.

  3. Browse by arrow, key or swipe

    The next image arrives from the direction you moved. A swipe follows your finger and the ends resist.

  4. Focus is handled

    Focus stays inside the viewer, the page behind does not scroll, and Escape closes it and returns focus to the thumbnail.

  5. Failed images are handled

    A broken image shows a labelled fallback without changing the gallery’s size.

  6. Real proportions

    Each image has its own width and height, so wide and tall pictures sit in the grid without being cropped in the viewer.

Overview

A gallery with a sense of place. Select a study and the image grows from its thumbnail into a full-screen viewer, keeping its proportions. Its caption follows a moment later. Browse with the arrows, keyboard or a swipe; the next study arrives from the direction you moved. Close it and the current image returns to its own thumbnail. The viewer is a native modal dialog, so the page behind it stays inert and keyboard focus stays inside.

States

open
The viewer measures the thumbnail and destination, then expands the image over 560ms. The caption follows after 180ms.
browse
Previous and next images enter from the direction of travel in 380ms. Navigation stops at the ends.
swipe
The image follows horizontal dragging. A 64px drag or a deliberate quick flick advances; a short drag settles back. The ends resist movement.
close
The current image returns to its measured thumbnail in 380ms. If its thumbnail has left the viewport, it fades away instead.
unavailable
A failed image shows a labelled fallback without changing the gallery’s dimensions.

Usage

usage.tsx
import { ExpandingGallery } from "@/components/expanding-gallery";<ExpandingGallery  label="Selected work"  images={[    { id: "campaign", src: "/images/campaign.webp", alt: "Amber bottle in afternoon light", title: "Afternoon study", width: 1536, height: 1024, meta: "Campaign · 2026" },    { id: "detail", src: "/images/detail.webp", alt: "A close-up of the bottle", title: "The essential form", width: 1536, height: 1024 },  ]}/>

Depends on lucide-react, installed for you by the CLI along with the keyframes it needs.

Works with

Track the selected study

Use stable image IDs and real intrinsic dimensions. Supply your own local or remote image URLs.

example.tsx
import { ExpandingGallery, type GalleryImage } from "@/components/expanding-gallery";export function Portfolio({ studies }: { studies: GalleryImage[] }) {  return (    <ExpandingGallery      images={studies}      label="Studio / Selected studies"      onImageChange={(image) => {        if (image) console.log("Opened study", image.id);      }}    />  );}

Props

images
GalleryImage[]
Stable id, src, alt, title, width and height; optional description and meta. Intrinsic proportions are preserved.
label= Selected work
string
The gallery heading and viewer heading.
onImageChange
(image: GalleryImage | null) => void
Called when a study opens or changes. Receives null on close.
className
string
Additional classes on the gallery root. Standard div attributes are forwarded.

Accessibility and motion

  • The viewer is a top-layer popover with role="dialog" and aria-modal: it opens above everything without making the page inert, which on a large page restyles every element in the frame it opens. Focus is trapped inside, the page behind does not scroll, Escape closes and focus returns to the current thumbnail, including after browsing.
  • Left and Right browse, Home and End jump to the first and last image. Buttons expose disabled states at the ends.
  • Pointer cancellation restores the image. Horizontal swipes leave vertical touch movement to the browser.
  • Reduced motion removes expansion, sliding, overshoot and thumbnail zoom. Navigation and all controls remain available.
  • Image IDs must be unique; width and height should match the source asset. The component handles an empty collection.
  • The entry point, viewer and motion helpers install together. No global animation stylesheet or animation library is required.

Requirements

React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

The CLI also installs Number roll, Text morph.

Source

'use client';import * as React from 'react';import { ArrowUpRight } from 'lucide-react';import { GalleryViewer } from './gallery-viewer';import { GalleryPicture, type GalleryImage } from './gallery-picture';import { INTERACTION_FOCUS } from './ui-interaction-motion';import { NumberRoll } from './number-roll';export type { GalleryImage } from './gallery-picture';export interface ExpandingGalleryProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'onSelect'> {  images: GalleryImage[];  label?: string;  onImageChange?: (image: GalleryImage | null) => void;}/** An image keeps its identity from the thumbnail to the viewer and back. */export function ExpandingGallery({ images, label = 'Selected work', onImageChange, className = '', ...props }: ExpandingGalleryProps) {  const [selected, setSelected] = React.useState<string | null>(null);  const frames = React.useRef(new Map<string, HTMLDivElement>());  const triggers = React.useRef(new Map<string, HTMLButtonElement>());  const [openingRect, setOpeningRect] = React.useState<DOMRect | null>(null);  const index = images.findIndex((image) => image.id === selected);  const visible = index >= 0;  const select = (next: number) => {    const image = images[next];    if (!image) return;    if (selected === null) setOpeningRect(frames.current.get(image.id)?.getBoundingClientRect() ?? null);    setSelected(image.id);    onImageChange?.(image);  };  const close = () => {    setSelected(null);    setOpeningRect(null);    onImageChange?.(null);    // Focus returns to the thumbnail of the image you were on, including after browsing.    triggers.current.get(selected ?? '')?.focus({ preventScroll: true });  };  return (    <div className={`w-full text-foreground ${className}`} {...props}>      <div className="mb-5 flex items-baseline justify-between gap-4">        <span className="text-[13px] font-medium">{label}</span>        <span className="font-mono text-[10px] uppercase tracking-[0.16em] text-muted-foreground"><NumberRoll value={images.length} format={{ minimumIntegerDigits: 2 }} /> studies</span>      </div>      <div className="grid grid-cols-2 gap-x-3 gap-y-5 sm:gap-x-4">        {images.map((image, i) => (          <button key={image.id} type="button" aria-label={`Open ${image.title}`} aria-haspopup="dialog"            ref={(el) => { if (el) triggers.current.set(image.id, el); else triggers.current.delete(image.id); }}            onClick={() => select(i)} className={`group min-w-0 cursor-zoom-in rounded-2xl text-left ${INTERACTION_FOCUS}`}>            <div ref={(el) => { if (el) frames.current.set(image.id, el); else frames.current.delete(image.id); }}              className="relative overflow-hidden rounded-2xl bg-muted" style={{ aspectRatio: `${Math.max(1, image.width)} / ${Math.max(1, image.height)}`, visibility: visible && selected === image.id ? 'hidden' : undefined }}>              <div className="size-full transition-transform duration-500 ease-out group-hover:scale-[1.025] motion-reduce:transform-none">                <GalleryPicture key={image.src} image={image} />              </div>              <span className="absolute bottom-3 right-3 flex size-7 items-center justify-center rounded-full border border-border bg-background text-foreground opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100 [@media(hover:none)]:opacity-100">                <ArrowUpRight className="size-3.5" aria-hidden="true" />              </span>            </div>            <span className="mt-2.5 flex items-baseline justify-between gap-2 px-0.5">              <span className="truncate text-[12px] font-medium">{image.title}</span>              <span className="font-mono text-[10px] text-muted-foreground">{String(i + 1).padStart(2, '0')}</span>            </span>            {image.meta && <span className="mt-0.5 block truncate px-0.5 text-[11px] text-muted-foreground">{image.meta}</span>}          </button>        ))}      </div>      {visible && <GalleryViewer images={images} index={index} label={label} openingRect={openingRect} getOrigin={(id) => frames.current.get(id)} onSelect={select} onClose={close} />}    </div>  );}

Registry item: /r/expanding-gallery.json