Explore the index
Browse components
SystemsstableReactWeb Animations APICSS Grid

Reflow Grid

Filter the shelf. The objects find their new places.

Filter, sort, switch to list, then search for something that does not exist.

A real browser viewport. Scroll within the preview when the sample needs more space. Configuration stays in sync between sizes.

01What it does

A generic collection grid with FLIP movement, animated entry and exit, and a real empty state. Filtering and sorting keep existing nodes and move them from their previous slots instead of rebuilding the grid.

In this previewA working object archive with category filters, search, three sort orders, grid/list switching, save toggles and an add action. The collection has ten objects and enough states to exercise removal, insertion and empty results.

Design decisions

Position is captured with offsetLeft/offsetTop rather than getBoundingClientRect, so an in-flight transform cannot contaminate the next measurement.

Removed cards become absolutely positioned ghosts at their old coordinates. The remaining cards can reflow immediately, which avoids the two-stage pause of waiting for an exit before measuring.

The component is generic and has no opinion about artwork. It owns movement, identity and focus; the consumer owns the card.

02Install

Registry install

registry:component

Run this in a React project with components.json. The component and its stylesheet land in components/lab/reflow-grid/.

npx shadcn@latest add https://lab.tanishk.me/r/reflow-grid.json

Files included

2
  • components/lab/reflow-grid/reflow-grid.tsxcomponent
  • components/lab/reflow-grid/reflow-grid.cssstyles

Manual install: copy each file into the same folder and preserve its relative imports. Open the source

03Usage

reflow-grid.usage.tsx
"use client";
import { useMemo, useState } from "react";
import { ReflowGrid } from "@/components/lab/reflow-grid/reflow-grid";

type Object = { id: string; name: string; category: string };

export function Archive({ objects }: { objects: Object[] }) {
const [category, setCategory] = useState("All");
const items = useMemo(
() => objects.filter((object) => category === "All" || object.category === category),
[objects, category],
);
return (
<>
<button onClick={() => setCategory("Lighting")}>Lighting</button>
<ReflowGrid
items={items}
getKey={(object) => object.id}
label="Object archive"
renderItem={(object) => <article>{object.name}</article>}
/>
</>
);
}

04Props

Props accepted by Reflow Grid
PropTypeDefaultNotes
itemsT[]—The current ordered collection.
getKey(item: T) => string—Stable identity for each record; required for movement and focus.
renderItem(item: T, context: { mode: "grid" | "list" }) => ReactNode—Renders one card. Fill the grid cell for equal rows.
mode"grid" | "list""grid"Two layout modes; switching runs the same measured animation.
emptyReactNode—Content for the empty state. A quiet default is provided.
labelstring"Collection"Accessible name for the region.
animatebooleantrueTurn off layout motion without changing the result.
gapnumber14Grid gap in pixels.
classNamestring—Forwarded to the root for local layout.

05Accessibility

  • The grid is a labelled region with a list and list items, and an empty result is exposed as a status message.
  • FLIP is measured from offset positions, so a running animation never feeds a wrong starting point into the next filter.
  • Removed cards leave as inert, aria-hidden ghosts for 220ms; they cannot receive pointer or keyboard focus.
  • If the focused card is removed by a host update, focus moves to the labelled region instead of being dropped on the document.
  • Reduced motion removes movement and exit animation, and the animate prop provides an explicit off switch.

06Source

2 files, 359 lines. The combined copy is a reference; save each file separately for use.

components/lab/reflow-grid/reflow-grid.tsx— press enter to show or hide the source
tsx
"use client";

import {
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
type CSSProperties,
type ReactNode,
} from "react";
import "./reflow-grid.css";

export type ReflowGridProps<T> = {
items: T[];
getKey: (item: T) => string;
renderItem: (item: T, context: { mode: "grid" | "list" }) => ReactNode;
mode?: "grid" | "list";
empty?: ReactNode;
label?: string;
/** Disable layout animation without changing the rendered result. */
animate?: boolean;
/** Space between cards, in pixels. */
gap?: number;
className?: string;
};

type Box = { x: number; y: number; width: number; height: number };

function prefersReduced() {
return (
typeof window !== "undefined" &&
window.matchMedia?.("(prefers-reduced-motion: reduce)").matches
);
}

/**
* REFLOW GRID
*
* Filtering and sorting keep the same DOM nodes and animate from their
* previous slots with a FLIP pass measured in layout space (offset
* coordinates, so a running animation never feeds back into the next
* measurement). Removed cards leave as short-lived, inert ghosts at
* their old coordinates; the survivors move at the same time instead of
* waiting for a second layout. Empty, grid, list and narrow states all
* share one component.
*/
export function ReflowGrid<T>({
items,
getKey,
renderItem,
mode = "grid",
empty,
label = "Collection",
animate = true,
gap = 14,
className,
}: ReflowGridProps<T>) {
const rootRef = useRef<HTMLDivElement>(null);
const nodes = useRef(new Map<string, HTMLElement>());
const boxes = useRef(new Map<string, Box>());
const known = useRef(new Map<string, T>());
const knownMode = useRef(mode);
const knownGap = useRef(gap);
const keysRef = useRef<string[]>([]);
const animations = useRef(new Map<string, Animation>());
const focusKey = useRef<string | null>(null);
const ghostTimer = useRef<number | null>(null);
const [ghosts, setGhosts] = useState<
{ key: string; box: Box; node: ReactNode }[]
>([]);

const keys = items.map(getKey);
const signature = keys.join("\u0001");
const previousSignature = useRef(signature);

const setNode = useCallback((key: string, node: HTMLElement | null) => {
if (node) nodes.current.set(key, node);
else nodes.current.delete(key);
}, []);

useLayoutEffect(() => {
const root = rootRef.current;
if (!root) return;
const changed =
previousSignature.current !== signature ||
knownMode.current !== mode ||
knownGap.current !== gap;
const reduced = prefersReduced() || !animate;

const nextBoxes = new Map<string, Box>();
for (const key of keys) {
const node = nodes.current.get(key);
if (!node) continue;
nextBoxes.set(key, {
x: node.offsetLeft,
y: node.offsetTop,
width: node.offsetWidth,
height: node.offsetHeight,
});
}

if (changed && !reduced) {
for (const key of keys) {
const node = nodes.current.get(key);
const before = boxes.current.get(key);
const after = nextBoxes.get(key);
if (!node || !before || !after) continue;
const dx = before.x - after.x;
const dy = before.y - after.y;
if (Math.abs(dx) < 0.5 && Math.abs(dy) < 0.5) continue;
animations.current.get(key)?.cancel();
const animation = node.animate(
[
{ transform: `translate3d(${dx}px, ${dy}px, 0)` },
{ transform: "translate3d(0, 0, 0)" },
],
{
duration: 340,
easing: "cubic-bezier(0.22, 1, 0.36, 1)",
},
);
animations.current.set(key, animation);
animation.finished
.catch(() => {})
.finally(() => {
if (animations.current.get(key) === animation)
animations.current.delete(key);
});
}

const seen = new Set(keysRef.current);
for (const key of keys) {
if (seen.has(key)) continue;
const node = nodes.current.get(key);
if (!node) continue;
animations.current.get(key)?.cancel();
const animation = node.animate(
[
{ opacity: 0, transform: "scale(0.975)" },
{ opacity: 1, transform: "scale(1)" },
],
{ duration: 260, easing: "cubic-bezier(0.22, 1, 0.36, 1)" },
);
animations.current.set(key, animation);
}

const removed = keysRef.current.filter((key) => !keys.includes(key));
if (removed.length) {
const leaving = removed.flatMap((key) => {
const box = boxes.current.get(key);
const item = known.current.get(key);
if (!box || item === undefined) return [];
return [
{
key,
box,
node: renderItem(item, { mode: knownMode.current }),
},
];
});
if (leaving.length) {
setGhosts(leaving);
if (ghostTimer.current !== null)
window.clearTimeout(ghostTimer.current);
ghostTimer.current = window.setTimeout(() => {
setGhosts([]);
ghostTimer.current = null;
}, 230);
}
}
}

boxes.current = nextBoxes;
keysRef.current = keys;
knownMode.current = mode;
knownGap.current = gap;
previousSignature.current = signature;
for (const item of items) known.current.set(getKey(item), item);
for (const key of [...known.current.keys()]) {
if (!keys.includes(key)) known.current.delete(key);
}

if (
focusKey.current &&
!keys.includes(focusKey.current) &&
(document.activeElement === document.body ||
!root.contains(document.activeElement))
) {
focusKey.current = null;
root.focus({ preventScroll: true });
}
}, [signature, mode, animate, gap, keys, items, getKey, renderItem]);

useEffect(
() => () => {
if (ghostTimer.current !== null) window.clearTimeout(ghostTimer.current);
for (const animation of animations.current.values()) animation.cancel();
animations.current.clear();
},
[],
);

const style = {
"--rg-gap": `${gap}px`,
} as CSSProperties;

return (
<div
ref={rootRef}
className={`rg-root${className ? ` ${className}` : ""}`}
data-mode={mode}
role="region"
aria-label={label}
tabIndex={-1}
style={style}
onFocusCapture={(event) => {
const item = (event.target as HTMLElement).closest<HTMLElement>(
"[data-reflow-key]",
);
focusKey.current = item?.dataset.reflowKey ?? null;
}}
>
{items.length === 0 ? (
<div className="rg-empty" role="status">
{empty ?? "Nothing matches these filters."}
</div>
) : (
<div className="rg-grid" role="list">
{items.map((item) => {
const key = getKey(item);
return (
<div
key={key}
ref={(node) => setNode(key, node)}
className="rg-item"
role="listitem"
data-reflow-key={key}
>
{renderItem(item, { mode })}
</div>
);
})}
</div>
)}
{ghosts.length > 0 ? (
<div className="rg-ghosts" aria-hidden="true" inert>
{ghosts.map((ghost) => (
<div
key={`ghost-${ghost.key}`}
className="rg-ghost"
style={{
left: ghost.box.x,
top: ghost.box.y,
width: ghost.box.width,
height: ghost.box.height,
}}
>
{ghost.node}
</div>
))}
</div>
) : null}
</div>
);
}
components/lab/reflow-grid/reflow-grid.css— press enter to show or hide the source
css
.rg-root {
position: relative;
min-width: 0;
font: inherit;
}

.rg-root:focus-visible {
outline: 2px solid #4b3f95;
outline-offset: 4px;
border-radius: 8px;
}

.rg-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(min(210px, 100%), 1fr));
gap: var(--rg-gap, 14px);
align-items: stretch;
}

.rg-root[data-mode="grid"] .rg-item {
min-width: 0;
height: 100%;
}

.rg-root[data-mode="grid"] .rg-item > * {
height: 100%;
}

.rg-root[data-mode="list"] .rg-grid {
grid-template-columns: minmax(0, 1fr);
gap: 8px;
}

.rg-root[data-mode="list"] .rg-item {
min-width: 0;
}

.rg-empty {
display: grid;
place-items: center;
min-height: 210px;
padding: 28px;
border: 1px dashed rgba(20, 20, 24, 0.16);
border-radius: 12px;
color: #71717a;
font-size: 0.875rem;
text-align: center;
}

.rg-ghosts {
position: absolute;
inset: 0;
z-index: 2;
pointer-events: none;
}

.rg-ghost {
position: absolute;
overflow: hidden;
border-radius: 12px;
animation: rg-ghost-out 220ms cubic-bezier(0.4, 0, 1, 1) both;
will-change: opacity, transform;
}

@keyframes rg-ghost-out {
from {
opacity: 1;
transform: scale(1);
}
to {
opacity: 0;
transform: scale(0.96);
}
}

@media (max-width: 520px) {
.rg-grid {
grid-template-columns: repeat(auto-fill, minmax(min(160px, 100%), 1fr));
gap: 10px;
}

.rg-root[data-mode="grid"] .rg-item > * {
height: auto;
}
}

@media (prefers-reduced-motion: reduce) {
.rg-ghost {
animation-duration: 0.01ms;
}
}