Menu

Components

Grid List

A list of rows that can be chosen, opened, moved, and hold buttons and other controls of their own.

Introduction

A grid list is a list where each row does more than one thing: it can be chosen, opened, moved, and hold buttons of its own, such as a menu, a delete button or a switch. That is the difference from a List Box, whose items are only chosen and cannot hold controls.

  • Choose one row, several (each with a checkbox), or none; or run an action or follow a link when a row is pressed.
  • Put buttons and other controls at the end of a row with actions. Pressing one does not choose the row.
  • Give onReorder and every row gets a handle: rows are dragged with the mouse or a finger, or moved with the keyboard.
  • Icons and avatars, a description under the title, sections, three variants and three sizes.
  • Built on react-aria's GridList: the up and down arrows move between rows, the left and right arrows into the controls in a row, and a screen reader hears the row and what is in it.

Installation

centerUI has no CLI or registry yet: components are copied into your project.

# bun
bun add react-aria-components tailwind-variants tailwind-merge clsx

# pnpm
pnpm add react-aria-components tailwind-variants tailwind-merge clsx

# npm
npm install react-aria-components tailwind-variants tailwind-merge clsx

Manual installation

Grid List uses the Avatar for the avatars of its rows and the grip icon of the icons file. Copy these files into your project and keep the paths, or adjust the imports.

1. Add the styles

src/types/grid-list-styles.tsShow code
import { tv } from "tailwind-variants";

// Styles for GridList. A row reads its state (focused, selected, dragged...)
// from data attributes that react-aria sets on it.
export const gridListStyles = tv({
  slots: {
    root: "flex w-full flex-col gap-1.5",
    label: "text-sm font-medium",
    description: "m-0 text-sm text-muted-fg",
    list: [
      "flex flex-col outline-none",
      "data-focus-visible:ring-2 data-focus-visible:ring-ring data-focus-visible:ring-offset-2 data-focus-visible:ring-offset-bg",
      "data-drop-target:bg-primary/5",
    ],
    empty: "px-3 py-8 text-center text-sm text-muted-fg",
    section: "not-first:mt-1 not-first:border-t not-first:pt-1",
    heading: "px-2.5 py-1.5 text-xs font-medium text-muted-fg",
    item: [
      "group/item relative flex cursor-default items-center gap-3 rounded-lg text-sm outline-none select-none",
      "data-hovered:bg-muted/60 data-focused:bg-muted/60 data-pressed:bg-muted/80",
      "data-selected:bg-muted data-selected:data-hovered:bg-muted",
      "data-focus-visible:ring-2 data-focus-visible:ring-ring data-focus-visible:ring-inset",
      "data-disabled:cursor-not-allowed data-disabled:opacity-50",
      "data-dragging:opacity-50 data-drop-target:bg-primary/10 data-drop-target:ring-2 data-drop-target:ring-primary/60 data-drop-target:ring-inset",
      "[&[href]]:cursor-pointer",
    ],
    // The box before a row, for a list where several rows are chosen.
    checkbox: [
      "flex size-4 shrink-0 items-center justify-center rounded border bg-bg text-primary-fg transition-colors [&_svg]:size-3",
      "data-selected:border-primary data-selected:bg-primary",
      "data-focus-visible:ring-2 data-focus-visible:ring-ring data-focus-visible:ring-offset-2 data-focus-visible:ring-offset-bg",
    ],
    handle: [
      "-ml-1 flex size-6 shrink-0 cursor-grab items-center justify-center rounded text-muted-fg outline-none [&_svg]:size-4",
      "hover:text-fg data-focus-visible:ring-2 data-focus-visible:ring-ring active:cursor-grabbing",
    ],
    icon: "shrink-0 text-muted-fg [&_svg]:size-4",
    text: "flex min-w-0 flex-1 flex-col",
    title: "truncate",
    itemDescription: "truncate text-xs text-muted-fg",
    // Room for buttons and other controls at the end of the row.
    actions: "ml-auto flex shrink-0 items-center gap-1",
    dropIndicator: [
      "relative h-0 outline-none",
      "data-drop-target:after:absolute data-drop-target:after:inset-x-2 data-drop-target:after:-top-px data-drop-target:after:h-0.5 data-drop-target:after:rounded-full data-drop-target:after:bg-primary",
    ],
  },
  variants: {
    variant: {
      outline: { list: "gap-0.5 rounded-xl border bg-card p-1 text-card-fg" },
      plain: { list: "gap-0.5" },
      // Rows with a line between them, and no space around.
      divided: {
        list: "divide-y overflow-hidden rounded-xl border bg-card text-card-fg",
        item: "rounded-none",
      },
    },
    size: {
      sm: { item: "px-2.5 py-1.5" },
      md: { item: "px-3 py-2.5" },
      lg: { item: "px-4 py-3.5" },
    },
  },
  defaultVariants: { variant: "outline", size: "md" },
});

2. Add the helper for reordering

src/types/grid-list-utils.tsShow code
import type { Key } from "react-aria-components";

/** Where a row was dropped: before a row, after it, or on it. */
export interface GridListDropTarget {
  key: Key;
  dropPosition: "before" | "after" | "on";
}

/** A row that was dragged from a list, as the list it was dropped in receives it: its key, and what `getDragData` gave. */
export interface GridListDraggedItem {
  key: Key;
  [data: string]: unknown;
}

/** What `onInsert` of a `GridList` says: the rows that were dropped, and where. `target` is `null` when they were dropped on the list itself, which is how an empty list is dropped on. */
export interface GridListInsertEvent {
  items: GridListDraggedItem[];
  target: GridListDropTarget | null;
}

/** What `onItemDrop` of a `GridList` says: the rows that were dropped, and the row they were dropped on. */
export interface GridListItemDropEvent {
  items: GridListDraggedItem[];
  target: { key: Key };
}

/** What `onReorder` of a `GridList` says: the rows that were moved, and where. */
export interface GridListReorderEvent {
  keys: Set<Key>;
  target: GridListDropTarget;
}

/**
 * The list after the rows of a reorder were moved: the moved rows, in the order
 * they had, put before or after the row they were dropped by. Use it in
 * `onReorder`, with the same function that finds the key of a row (`getKey`).
 *
 * @example
 * onReorder={(event) => setItems((list) => moveItems(list, event, (item) => item.id))}
 */
export function moveItems<T>(
  list: T[],
  { keys, target }: GridListReorderEvent,
  getKey: (item: T) => Key,
): T[] {
  const moved = list.filter((item) => keys.has(getKey(item)));
  const rest = list.filter((item) => !keys.has(getKey(item)));
  const at = rest.findIndex((item) => getKey(item) === target.key);
  if (at === -1) return list;
  const index = target.dropPosition === "before" ? at : at + 1;
  return [...rest.slice(0, index), ...moved, ...rest.slice(index)];
}

3. Add the Grid List file

src/components/ui/grid-list/grid-list.tsxShow code
"use client";

import { createContext, type ReactNode, useContext, useId } from "react";
import {
  Button as AriaButton,
  Checkbox as AriaCheckbox,
  GridList as AriaGridList,
  GridListHeader as AriaGridListHeader,
  GridListItem as AriaGridListItem,
  type GridListItemProps as AriaGridListItemProps,
  type GridListProps as AriaGridListProps,
  GridListSection as AriaGridListSection,
  DropIndicator,
  type DropItem,
  type Key,
  Text,
  useDragAndDrop,
} from "react-aria-components";
import { CheckIcon, GripVerticalIcon } from "@/components/icons";
import { Avatar, type AvatarProps } from "@/components/ui/avatar/avatar";
import { cn } from "@/lib/cn";
import { cx } from "@/lib/primitive";
import { gridListStyles } from "@/types/grid-list-styles";
import type {
  GridListDraggedItem,
  GridListInsertEvent,
  GridListItemDropEvent,
  GridListReorderEvent,
} from "@/types/grid-list-utils";

interface ListContext {
  size: "sm" | "md" | "lg";
  variant: "outline" | "plain" | "divided";
}

const ListContext = createContext<ListContext>({
  size: "md",
  variant: "outline",
});

const styles = gridListStyles();

export interface GridListProps<T extends object>
  extends Omit<
    AriaGridListProps<T>,
    | "className"
    | "style"
    | "aria-label"
    | "aria-labelledby"
    | "dragAndDropHooks"
    | "renderEmptyState"
  > {
  /** A label above the list, which also names it for screen readers. Without one, name the list with `aria-label`. */
  label?: ReactNode;
  /** A line that says more, under the label. */
  description?: ReactNode;
  /** Names the list for screen readers when there is no `label`. */
  "aria-label"?: string;
  /** A box with a border around the rows, the rows alone, or rows with a line between them. Defaults to `outline`. */
  variant?: "outline" | "plain" | "divided";
  /** How much room each row has. Defaults to `md`. */
  size?: "sm" | "md" | "lg";
  /**
   * Called when rows are dragged to a new place. Setting it gives every row a
   * handle, and rows can be moved with the mouse, a finger or the keyboard (Enter
   * on the handle, the arrow keys, Enter again). Use `moveItems` to make the new
   * list.
   */
  onReorder?: (event: GridListReorderEvent) => void;
  /**
   * Makes the rows draggable to other lists, and gives back what goes with a
   * row: `(key) => ({ name: "Report.pdf" })`. The list that receives it gets
   * that object, with the `key`, in `onInsert` or `onItemDrop`.
   */
  getDragData?: (key: Key) => object;
  /**
   * The kind of drag this list gives and takes. Two lists that should exchange
   * rows have the same one, and lists that should not have another. Defaults to
   * `application/x-centerui-row`.
   */
  dragType?: string;
  /**
   * Called when rows from another list are dropped between rows, or on the list
   * when it is empty (`target` is then `null`). The rows are not taken out of the
   * list they came from: do that here, as you put them in.
   */
  onInsert?: (event: GridListInsertEvent) => void;
  /** Called when rows are dropped on a row: a folder, a project, a trash. See `canDropOn`. */
  onItemDrop?: (event: GridListItemDropEvent) => void;
  /** Which rows rows can be dropped on. Defaults to none: set it with `onItemDrop`. */
  canDropOn?: (key: Key) => boolean;
  /** What it says when there are no rows. Defaults to "Nothing here." */
  emptyMessage?: ReactNode;
  className?: string;
}

/**
 * A list of rows, where each row can hold buttons and other controls as well as
 * being chosen: a list of files with a menu on each, tasks with a delete button,
 * people with a switch. That is what makes it different from a List Box, whose
 * items are only chosen. Rows can be chosen (one, several, or none), be links or
 * run an action, and be dragged to a new order.
 *
 * Built on react-aria's GridList: the up and down arrows move between rows, the
 * left and right arrows move between the row and the controls inside it, and a
 * screen reader hears each row with what is in it. With several rows chosen a
 * checkbox shows in each row, and Shift and Ctrl or Command extend the choice.
 *
 * Give each `GridListItem` an `id`, which is what the selection holds, and put
 * controls in its `actions`.
 *
 * @example
 * <GridList aria-label="Files" selectionMode="multiple">
 *   <GridListItem id="a" icon={<FileIcon />} actions={<Button size="sm">Open</Button>}>
 *     Report.pdf
 *   </GridListItem>
 * </GridList>
 */
export function GridList<T extends object>({
  label,
  description,
  "aria-label": ariaLabel,
  variant = "outline",
  size = "md",
  onReorder,
  getDragData,
  dragType = "application/x-centerui-row",
  onInsert,
  onItemDrop,
  canDropOn,
  emptyMessage = "Nothing here.",
  className,
  children,
  ...props
}: GridListProps<T>) {
  const labelId = useId();
  const descriptionId = useId();
  const classes = gridListStyles({ variant, size });

  const isDraggable = Boolean(onReorder || getDragData);
  const canDrop = Boolean(onReorder || onInsert || onItemDrop);

  // What was dragged from a list comes as text under `dragType`.
  async function readItems(items: DropItem[]): Promise<GridListDraggedItem[]> {
    const texts = await Promise.all(
      items.map((item) =>
        item.kind === "text" && item.types.has(dragType)
          ? item.getText(dragType)
          : null,
      ),
    );
    return texts.flatMap((text) => (text ? [JSON.parse(text)] : []));
  }

  // The hook is always called: without any of the props above, its result is
  // not used.
  const { dragAndDropHooks } = useDragAndDrop({
    getItems: isDraggable
      ? (keys) =>
          [...keys].map((key) => ({
            "text/plain": String(key),
            [dragType]: JSON.stringify({ ...getDragData?.(key), key }),
          }))
      : undefined,
    getAllowedDropOperations: () => ["move"],
    acceptedDragTypes: [dragType],
    onReorder: onReorder
      ? (event) =>
          onReorder({
            keys: new Set(event.keys),
            target: {
              key: event.target.key,
              dropPosition: event.target.dropPosition,
            },
          })
      : undefined,
    onInsert: onInsert
      ? async (event) =>
          onInsert({
            items: await readItems(event.items),
            target: {
              key: event.target.key,
              dropPosition: event.target.dropPosition,
            },
          })
      : undefined,
    onRootDrop: onInsert
      ? async (event) =>
          onInsert({ items: await readItems(event.items), target: null })
      : undefined,
    onItemDrop: onItemDrop
      ? async (event) =>
          onItemDrop({
            items: await readItems(event.items),
            target: { key: event.target.key },
          })
      : undefined,
    shouldAcceptItemDrop: onItemDrop
      ? (target) => (canDropOn ? canDropOn(target.key) : false)
      : undefined,
    renderDropIndicator: (target) => (
      <DropIndicator target={target} className={styles.dropIndicator()} />
    ),
  });

  return (
    <div className={cn(classes.root(), className)}>
      {label ? (
        <span id={labelId} className={classes.label()}>
          {label}
        </span>
      ) : null}
      {description ? (
        <p id={descriptionId} className={classes.description()}>
          {description}
        </p>
      ) : null}
      <ListContext.Provider value={{ size, variant }}>
        <AriaGridList<T>
          {...props}
          dragAndDropHooks={
            isDraggable || canDrop ? dragAndDropHooks : undefined
          }
          aria-labelledby={label ? labelId : undefined}
          aria-label={label ? undefined : (ariaLabel ?? "List")}
          aria-describedby={description ? descriptionId : undefined}
          renderEmptyState={() => (
            <p className={classes.empty()}>{emptyMessage}</p>
          )}
          className={classes.list()}
        >
          {children}
        </AriaGridList>
      </ListContext.Provider>
    </div>
  );
}

export interface GridListItemProps extends AriaGridListItemProps {
  /** A second, smaller line under the label. */
  description?: ReactNode;
  /** An icon before the label. */
  icon?: ReactNode;
  /** An avatar before the label. */
  avatar?: AvatarProps;
  /**
   * Controls at the end of the row: buttons, a menu, a switch. They are reached
   * with the left and right arrow keys from the row, and pressing one does not
   * choose the row.
   */
  actions?: ReactNode;
}

/**
 * One row. `id` is the key that the selection and `onReorder` use. Give it a
 * `textValue` when its children are not plain text, so that typing a letter has
 * something to match.
 */
export function GridListItem({
  description,
  icon,
  avatar,
  actions,
  className,
  children,
  textValue,
  ...props
}: GridListItemProps) {
  const { size, variant } = useContext(ListContext);
  const classes = gridListStyles({ size, variant });

  return (
    <AriaGridListItem
      {...props}
      textValue={
        textValue ?? (typeof children === "string" ? children : undefined)
      }
      className={cx(classes.item(), className)}
    >
      {(renderProps) => (
        <>
          {renderProps.allowsDragging ? (
            <AriaButton slot="drag" className={classes.handle()}>
              <GripVerticalIcon />
            </AriaButton>
          ) : null}
          {renderProps.selectionMode === "multiple" &&
          renderProps.selectionBehavior === "toggle" ? (
            <AriaCheckbox slot="selection" className={classes.checkbox()}>
              {({ isSelected }) => (isSelected ? <CheckIcon /> : null)}
            </AriaCheckbox>
          ) : null}
          {avatar ? (
            <Avatar {...avatar} />
          ) : icon ? (
            <span aria-hidden="true" className={classes.icon()}>
              {icon}
            </span>
          ) : null}
          <span className={classes.text()}>
            <span className={classes.title()}>
              {typeof children === "function"
                ? children(renderProps)
                : children}
            </span>
            {description ? (
              <Text slot="description" className={classes.itemDescription()}>
                {description}
              </Text>
            ) : null}
          </span>
          {actions ? (
            <span className={classes.actions()}>{actions}</span>
          ) : null}
        </>
      )}
    </AriaGridListItem>
  );
}

export interface GridListSectionProps {
  /** The title of the group. */
  title: ReactNode;
  children: ReactNode;
}

/** A titled group of rows, separated from the group above it. */
export function GridListSection({ title, children }: GridListSectionProps) {
  return (
    <AriaGridListSection className={styles.section()}>
      <AriaGridListHeader className={styles.heading()}>
        {title}
      </AriaGridListHeader>
      {children}
    </AriaGridListSection>
  );
}

4. Use it

import {
  GridList,
  GridListItem,
  GridListSection,
} from "@/components/ui/grid-list/grid-list";
import { moveItems } from "@/types/grid-list-utils"; // only to reorder

Anatomy

A list, its rows, and if you like, groups.

<GridList label="Files" selectionMode="multiple" onReorder={reorder}>
  <GridListSection title="Recent">
    <GridListItem id="a" icon={<FileIcon />} description="2.4 MB" actions={<Button size="xs">Open</Button>}>
      Report.pdf
    </GridListItem>
  </GridListSection>
</GridList>
PartRendered asNotes
GridListgridThe list. It has the focus, and the up and down arrows move between rows.
GridListSectionrowgroupA titled group of rows.
GridListItemrowOne row: a handle when it can be moved, a checkbox when several can be chosen, an icon or avatar, a title with a description, and controls at the end.

Keyboard

KeyWhat it does
TabMoves into the list, to the focused row or the first, and out of it.
↓ ↑Moves to the next or the previous row.
→ ←Moves between the row and the controls inside it: the checkbox, the handle, the buttons.
SpaceChooses the row, in a list that can choose.
EnterRuns the action of the row, or opens its link.
Shift + ↓ ↑In a list of several, extends the choice.
Ctrl or ⌘ + AIn a list of several, chooses all.
EscapeClears the choice, in a list of several.
Enter on the handleStarts moving the row: ↓ ↑ pick the place, Enter drops it, Escape cancels.

Examples

Usage

Each row needs an id.

Documents
Report.pdf2.4 MB
Budget.xlsx180 KB

Choosing rows

With selectionMode multiple, each row has a checkbox. Shift and Ctrl or Command extend the choice.

Files
Report.pdf2.4 MB
Budget.xlsx180 KB
Photo.png4.1 MB

Selected: budget

Controls in a row

Buttons in actions are their own targets: they are reached with the arrow keys, and pressing one does not run the action of the row. The list's onAction runs when the row itself is pressed.

Write the docs
Review the pull request
Ship it

Last action: nothing yet

Reordering

onReorder gives every row a handle. moveItems makes the new list from what the event says.

To do
In progress
In review
Done

Order: todo → doing → review → done

Drag between lists

Two lists with the same dragType exchange rows. getDragData makes a list's rows draggable and says what goes with each. The list that receives rows is told in onInsert, where they are dropped, or with a target of null when it is dropped on while empty. The rows are not taken out of the list they came from: do it there, as you put them in. Rows can also be moved by keyboard: Enter on the handle, the arrow keys to a place (in another list too), Enter to drop.

Backlog (3)
Write the docs
Review the pull request
Fix the focus ring
Done (1)
Set up the project

Drop on a row

onItemDrop with canDropOn makes rows that can be dropped on: a folder, a project, a trash. In a list that can choose several rows, all the chosen rows are dragged together.

Files
Report.pdf
Budget.xlsx
Photo.png
Notes.txt
Folders
DocumentsEmpty
PicturesEmpty
ArchiveEmpty

Rich rows

An avatar or an icon, a second line, and controls at the end.

Ada LovelaceEngineer
Alan TuringResearcher
Grace HopperDesigner

Sections

Folders
Documents
Pictures
Files
Notes.txt

Disabled

Free
Pro
TeamComing soon

Variants

Alpha
Beta
Gamma
outline
Alpha
Beta
Gamma
plain
Alpha
Beta
Gamma
divided

Sizes

Alpha
Beta
sm
Alpha
Beta
md
Alpha
Beta
lg

Component API

GridList takes these props, and each GridListItem the second table. GridListSection takes a title.

GridList

PropTypeDefault
labelReactNode-
descriptionReactNode-
aria-labelstring"List"
selectionMode"none" | "single" | "multiple""none"
selectedKeys"all" | Iterable<Key>-
defaultSelectedKeys"all" | Iterable<Key>-
onSelectionChange(keys: Selection) => void-
disallowEmptySelectionbooleanfalse
selectionBehavior"toggle" | "replace""toggle"
disabledKeysIterable<Key>-
itemsIterable<T>-
onAction(key: Key) => void-
onReorder(event: GridListReorderEvent) => void-
variant"outline" | "plain" | "divided""outline"
size"sm" | "md" | "lg""md"
emptyMessageReactNode"Nothing here."
classNamestring-

GridListItem

PropTypeDefault
idKey-
childrenReactNode-
textValuestringthe title
descriptionReactNode-
iconReactNode-
avatarAvatarProps-
actionsReactNode-
hrefstring-
onAction() => void-
isDisabledbooleanfalse