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
Dir
Presets
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.
Code
<Gallery data={photos} min={160} ratio={1} loader={unsplash} />Change the cell shape with ratio:
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.
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:
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.
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
rowHeighton 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.
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:
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.
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.
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 photorole="listitem", so screen readers announce how many photos there are. Name it witharia-labelwhen 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, usegridorjustified, which keepdata'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>witharia-haspopup="dialog", named by its photo'salt. Withalt=""it's named bytranslations.openLabelinstead ("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
Canvassurface 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.
| Key | Default | Receives |
|---|---|---|
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
- #349
New
Galleryingrid,masonryorjustifiedlayout computed in CSS from each item'swidth/height, with captions,spacing,radius,loaderandrenderItem; wrap it in aLightboxand every tile opens the viewer - #351
Gallery adapts to its own width: justified rows shrink when narrow, masonry
columnstakes a breakpoint map ({ base: 2, md: 3 }) or fits frommin, and keyboard focus stays on its tile as columns change
Figure
Media with a caption, as a real figure and figcaption. The caption sits below the media, above it, or over its bottom edge on a scrim that keeps text readable on any photo.
Lightbox
A full-screen image viewer that grows out of the thumbnail you clicked, with swipe, pinch, zoom and drag-to-dismiss, and shrinks back into the tile of the image you end on.