|Kit

Gallery

A set of photos in a grid, masonry columns or justified rows. Every layout is plain CSS decided from each photo's size, so the server HTML is already the final layout.

Gallery lays out a list of photos, each one an Image. Give it data with each photo's width and height, and pick a layout. Nothing is measured in the browser: the layout comes from CSS and the photos' sizes, so it's correct in the server HTML and doesn't shift when the page hydrates.

import { Gallery } from '@42-central/ui-react/gallery';

const photos = [
  { src: '/photos/lake.jpg', alt: 'A mountain lake at dawn', width: 1600, height: 1067 },
  { src: '/photos/falls.jpg', alt: 'A waterfall under a stone bridge', width: 1067, height: 1600 },
  // …
];

<Gallery data={photos} layout="justified" loader={cdnLoader} />

Playground

Component

Loading preview

Props

Code

<Component
  layout="grid"
  rowHeight={200}
  columns={3}
/>

Full prop browser

Grid

The default. As many tracks as fit at min pixels wide (160 by default), with every cell cropped to ratio (square by default). A track is never wider than the gallery, so a gallery narrower than min shows one column instead of overflowing.

Blue mountains above a lake and a pine forest
A tall waterfall under a stone footbridge, in a mossy gorge
Pine trees fading into morning fog
A wooden footbridge leading into a dense forest
A desert road running between red rock walls
A spiral of grass on a green hill at sunset
The Milky Way over snowy peaks
Orange poppies against a blue sky
A granite cliff above a meadow and tall pines
Waves on a sandy beach at sunrise
Layered blue ridges under a pale dusk sky
Sunlight on a path through tall trees

Code

<Gallery data={photos} min={160} ratio={1} loader={unsplash} />

Change the cell shape with ratio:

Blue mountains above a lake and a pine forest
A tall waterfall under a stone footbridge, in a mossy gorge
Pine trees fading into morning fog
A wooden footbridge leading into a dense forest
A desert road running between red rock walls
A spiral of grass on a green hill at sunset
The Milky Way over snowy peaks
Orange poppies against a blue sky

Code

<Gallery data={photos} min={220} ratio="16/9" loader={unsplash} />

Masonry

columns columns of whole, uncropped photos. Each photo goes to the column that is shortest so far, which keeps the columns' heights close.

Blue mountains above a lake and a pine forest
A desert road running between red rock walls
A granite cliff above a meadow and tall pines
Sunlight on a path through tall trees
Low clouds over a green valley at sunset
Fog drifting over a forest, seen from above
A tall waterfall under a stone footbridge, in a mossy gorge
A spiral of grass on a green hill at sunset
Waves on a sandy beach at sunrise
Layered blue ridges under a pale dusk sky
A rocky shore under a purple dusk sky
Pine trees fading into morning fog
A wooden footbridge leading into a dense forest
The Milky Way over snowy peaks
Orange poppies against a blue sky
A snowy peak rising out of clouds
Rock spires on misty hills

Code

<Gallery data={photos} layout="masonry" columns={3} loader={unsplash} />

The photos sit in their columns in the DOM, so the reading order and the tab order run down the first column, then the second, and so on. Each item keeps its position in data as data-index, and that's the index the gallery opens. See Accessibility.

Responsive columns

columns is a fixed count, or one count per breakpoint: { base: 2, md: 3, lg: 4 }. The breakpoints are the kit's (xs 480, sm 640, md 768, lg 1024, xl 1280, 2xl 1536px), matched against the gallery's own width, not the viewport's, so a gallery in a sidebar gets its own count. Or give min, the narrowest a column may get, and the gallery fits as many columns as it can, the way a grid fits its tracks:

Blue mountains above a lake and a pine forest
Pine trees fading into morning fog
A wooden footbridge leading into a dense forest
A spiral of grass on a green hill at sunset
The Milky Way over snowy peaks
A granite cliff above a meadow and tall pines
Waves on a sandy beach at sunrise
Sunlight on a path through tall trees
A tall waterfall under a stone footbridge, in a mossy gorge
A desert road running between red rock walls
Orange poppies against a blue sky
Layered blue ridges under a pale dusk sky

Code

<Gallery data={photos} layout="masonry" columns={{ base: 2, xs: 3 }} />
<Gallery data={photos} layout="masonry" min={220} columns={2} />

This one has 2 columns below 480px of gallery width and 3 from there, whatever the viewport: narrow the window and it switches when the docs column does.

Both need the gallery's width, which only the browser knows, so they're the one part of Gallery that measures. The server HTML and the first paint use columns (the map's base, or 1 without one), then an observer measures the gallery and switches to the right count. Choose that starting count for your most common width, such as base for a mobile-first page, so most visitors see no change. With min, columns is only that starting count. A plain number needs no measuring: it's exact in the server HTML, and no observer is mounted.

Rendering one column set per breakpoint and hiding the others with CSS would avoid the switch, but every photo would then exist several times: as duplicate list items, duplicate test ids and duplicate tiles registered for the same index. One set and one switch is the simpler trade.

Justified

Rows that fill the width, with every photo whole and uncropped, as on Flickr or Google Photos. On a wide gallery the rows are rowHeight pixels high (200 by default); on a narrower one they get shorter, so a phone still fits about three photos across.

Blue mountains above a lake and a pine forest
A tall waterfall under a stone footbridge, in a mossy gorge
Pine trees fading into morning fog
A wooden footbridge leading into a dense forest
A desert road running between red rock walls
A spiral of grass on a green hill at sunset
The Milky Way over snowy peaks
Orange poppies against a blue sky
A granite cliff above a meadow and tall pines
Waves on a sandy beach at sunrise
Layered blue ridges under a pale dusk sky
Sunlight on a path through tall trees
A snowy peak rising out of clouds
Low clouds over a green valley at sunset
A rocky shore under a purple dusk sky
Rock spires on misty hills
Fog drifting over a forest, seen from above

Code

<Gallery data={photos} layout="justified" loader={unsplash} />

It's flexbox and CSS, with no JavaScript and nothing measured:

/* The gallery: an inline-size container, so 25cqi is a quarter of its width */
--row: clamp(96px, 25cqi, rowHeight);

/* Each item, for a photo of aspect ratio r */
flex: r 1 calc(var(--row) * r);
max-width: calc(var(--row) * r * (1 + tolerance));
aspect-ratio: r;
  • The row height follows the gallery's width. Three 4:3 photos side by side are four row heights wide, so a row height of a quarter of the width fits about three average photos a row. It stops at rowHeight on a wide gallery, and never goes under 96px, so thumbnails stay easy to tap in a narrow one.
  • Rows fill the width. Each photo starts at its width at that height and grows in proportion to its aspect ratio, so every photo on a row grows to the same height.
  • A row that can't be filled stops early. It grows by at most tolerance (25% by default), then ends short of the edge instead of blowing up its photos. That's always the last row, and sometimes a row whose next photo is too wide to fit. The more photos fit on a row, the smaller that gap, which is what scaling the row height is for.

The gallery takes its width from its parent, never from its photos. Inside a flex row, give it flex-1 or a width.

Captions

Give an item a caption to show it over the bottom of its photo, on Figure's overlay scrim. It keeps white text above 4.5:1 contrast over any photo, in both themes.

Blue mountains above a lake and a pine forest
Lake Louise, Alberta
A tall waterfall under a stone footbridge, in a mossy gorge
Multnomah Falls, Oregon
Pine trees fading into morning fog
Black Forest, Germany
A wooden footbridge leading into a dense forest
Hoh rainforest, Washington
A desert road running between red rock walls
Valley of Fire, Nevada
A spiral of grass on a green hill at sunset
Fairy Glen, Isle of Skye

Code

<Gallery data={photos.map((p) => ({ ...p, caption: p.place }))} ratio="4/3" />

Keep them to a line: a long caption covers the photo it describes.

Opening a photo

Gallery doesn't open anything by itself. It reads the open-index seam: when an OpenIndexProvider is above it, every tile becomes a button that calls open(index, element) with its position in data and its own element. A lightbox provides it, or your own code does, to open a route or a side panel. With no provider, the tiles stay plain images, and nothing in the gallery is focusable.

This demo's provider just logs what it gets. Click a photo, or tab to one and press Enter:

0 tiles registered. Click a photo, or Tab to one and press Enter.

Code

import { OpenIndexProvider, type OpenIndex } from '@42-central/ui-react';

const tiles = new Map<number, HTMLElement>();
const seam: OpenIndex = {
  open: (index, from) => console.log(index, from.getBoundingClientRect()),
  // Each tile registers while it's mounted. A tile that moves (masonry
  // switching its column count) registers its new element first, so only
  // remove the entry if it's still this element.
  register: (index, element) => {
    tiles.set(index, element);
    return () => {
      if (tiles.get(index) === element) tiles.delete(index);
    };
  },
};

<OpenIndexProvider value={seam}>
  <Gallery data={photos} />
</OpenIndexProvider>

register is how a viewer gets back to the right tile. Each tile registers its element under its index, so a lightbox opened on photo 2 and navigated to photo 5 can return focus, and animate, to photo 5's tile when it closes. Keep the provider's value stable (useMemo): every tile registers again when it changes.

Responsive

Every layout follows the gallery's own width. Drag the slider: the grid fits fewer tracks, justified rows get shorter, and masonry fits fewer 140px-wide columns.

Blue mountains above a lake and a pine forest
A tall waterfall under a stone footbridge, in a mossy gorge
Pine trees fading into morning fog
A wooden footbridge leading into a dense forest
A desert road running between red rock walls
A spiral of grass on a green hill at sunset
The Milky Way over snowy peaks
Orange poppies against a blue sky
A granite cliff above a meadow and tall pines
Waves on a sandy beach at sunrise
Layered blue ridges under a pale dusk sky
Sunlight on a path through tall trees

Code

<Gallery data={photos} layout="grid" min={120} />
<Gallery data={photos} layout="justified" />
<Gallery data={photos} layout="masonry" min={140} columns={2} />

Each layout also gets a default sizes, so a loader srcset fetches about the right width: twice min for a grid (a track never reaches it), one column's share of the viewport for masonry, and each photo's maximum width for justified rows. Pass sizes to override it for every photo.

Spacing and radius

spacing sets the gap on the kit's size scale (md, 8px, by default; none for a flush wall). radius rounds every photo like Image does, xs by default; "none" squares them.

Blue mountains above a lake and a pine forest
A tall waterfall under a stone footbridge, in a mossy gorge
Pine trees fading into morning fog
A wooden footbridge leading into a dense forest
A desert road running between red rock walls
A spiral of grass on a green hill at sunset
Blue mountains above a lake and a pine forest
A tall waterfall under a stone footbridge, in a mossy gorge
Pine trees fading into morning fog
A wooden footbridge leading into a dense forest
A desert road running between red rock walls
A spiral of grass on a green hill at sunset

Code

<Gallery data={photos} spacing="none" radius="none" />
<Gallery data={photos} spacing="xl" radius="lg" />

Custom tiles

renderItem(item, index, image) replaces a tile's media. image is the Image the gallery would have rendered, so you can wrap it, add a badge over it, or swap it for something else. The caption and the open button stay the gallery's. Under a provider, the media sits inside a <button>, so return phrasing content only: an Image, <span>s, no <div>s or links.

<Gallery
  data={photos}
  renderItem={(item, index, image) => (
    <span className="relative block size-full">
      {image}
      {item.video && <Badge className="absolute end-2 top-2">Video</Badge>}
    </span>
  )}
/>

Right-to-left

Every layout uses flexbox or grid with logical properties, so it follows the direction: rows and the grid fill from the right, masonry's first column is on the right, and captions are start-aligned. The page's direction toggle flips every demo on this page; this one is right-to-left with Arabic alt text, and its last two photos are decorative, so their buttons take the translated openLabel, with Arabic numerals from the locale.

بحيرة لويز، ألبرتا

Code

<IntlProvider locale="ar-EG">
  <div dir="rtl" lang="ar">
    <Gallery
      data={photos}
      layout="justified"
      translations={{ openLabel: (position, count) => `فتح الصورة ${position} من ${count}` }}
    />
  </div>
</IntlProvider>

API

Prop

Type

Every other <div> attribute goes to the root, aria-label included. No asChild.

GalleryItem

Prop

Type

OpenIndexProvider

Prop

Type

useOpenIndex() reads the nearest provider (undefined without one), and useOpenIndexTrigger(index) gives your own element the same opener props as a gallery tile. Both come from @42-central/ui-react; see useOpenIndex for a demo and their full API.

Accessibility

  • A list. The root has role="list" and every photo role="listitem", so screen readers announce how many photos there are. Name it with aria-label when the page has more than one.
  • Masonry reading order. Masonry puts its items in column containers (role="none"), which keep them direct items of the list. The reading order and the tab order run down each column in turn, which is not left to right across the rows. When order matters, as in a timeline, use grid or justified, which keep data's order.
  • Masonry column changes. When a measured masonry (a breakpoint map or min) switches its column count, its tiles move to new columns. A tile that had keyboard focus keeps it: focus follows the tile to its new place.
  • Buttons only when something opens. Under an OpenIndexProvider, each tile is a real <button> with aria-haspopup="dialog", named by its photo's alt. With alt="" it's named by translations.openLabel instead ("Open image 3 of 12"). With no provider, nothing is focusable.
  • Keyboard. Tab moves through the tiles; Enter or Space opens one.
  • A focus ring that isn't clipped. The ring is drawn on the item around the button, outside the overlay caption's clip, with the kit's offset gap.
  • Captions. Overlay captions keep Figure's 4.5:1 scrim, and its solid Canvas surface in forced colors. They're read after the photo, inside a <figure>. Under a provider, clicks on a caption go through to the tile's button.
  • Alt and caption. They do different jobs: don't repeat one in the other. See Figure.
  • Right-to-left. Logical properties only; see Right-to-left.

Internationalization

Gallery's one string of its own is the label of a decorative photo's open button. Alt text and captions are your content: translate them with the rest of the page.

KeyDefaultReceives
openLabel(position, count) => `Open image ${position} of ${count}` The 1-based position and the count, already formatted with Intl.NumberFormat for the locale from IntlProvider
<Gallery
  data={photos.map((photo) => ({ ...photo, alt: t('photos.alt', photo) }))}
  translations={{ openLabel: (position, count) => t('photos.open', { position, count }) }}
/>

Changelog

v0.20.0
  • New Gallery in grid, masonry or justified layout computed in CSS from each item's width/height, with captions, spacing, radius, loader and renderItem; wrap it in a Lightbox and every tile opens the viewer

    #349
  • Gallery adapts to its own width: justified rows shrink when narrow, masonry columns takes a breakpoint map ({ base: 2, md: 3 }) or fits from min, and keyboard focus stays on its tile as columns change

    #351

On this page