Menu

Components

Tag Group

A group of short labels that can be chosen, removed, or followed as links.

Introduction

Tags are short labels for what something is about: topics, filters, people, statuses. A tag group is for tags that a person works with, so they can be chosen, removed, or followed as links. A tag that only shows a status and does nothing is a Badge, and to type new tags into a field use a Tag Field.

  • Choose one tag, several, or none, with the selection controlled or left to the group.
  • Give onRemove and each tag gets a button to remove it, and Backspace or Delete does the same on a tag that has the focus.
  • A soft tint, a solid fill or an outline, four colors, three sizes, and a rounded or a pill shape. A chosen tag is filled with the primary color.
  • Icons and avatars, links, disabled tags, a label, a description and a line for an error.
  • Built on react-aria's TagGroup: the arrow keys move between tags, and a screen reader hears the group, each tag and whether it is chosen.

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

Tag Group uses the Avatar for the avatars of its tags. Copy these files into your project and keep the paths, or adjust the imports.

1. Add the styles

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

// Styles for TagGroup. The colors are those of Badge: `color` is the color
// (default, success, warning, danger) and `appearance` is how it is used (soft
// tint, solid fill, or an outline). A tag that is selected is filled with the
// primary color, whatever its own.
export const tagGroupStyles = tv({
  slots: {
    root: "flex w-full flex-col gap-1.5",
    label: "text-sm font-medium",
    description: "m-0 text-sm text-muted-fg",
    error: "m-0 text-sm text-danger",
    list: "flex flex-wrap items-center outline-none",
    empty: "text-sm text-muted-fg",
    tag: [
      "group/tag inline-flex max-w-full cursor-default items-center gap-1.5 font-medium outline-none select-none",
      "transition-colors",
      "data-focus-visible:ring-2 data-focus-visible:ring-ring data-focus-visible:ring-offset-2 data-focus-visible:ring-offset-bg",
      "data-disabled:cursor-not-allowed data-disabled:opacity-50",
      "data-selected:border-transparent data-selected:bg-primary data-selected:text-primary-fg data-selected:ring-0",
      "[&[href]]:cursor-pointer",
    ],
    icon: "flex shrink-0 items-center justify-center [&_svg]:size-[1em]",
    label_: "truncate",
    remove: [
      "-mr-1 flex shrink-0 cursor-pointer items-center justify-center rounded-full opacity-70 outline-none transition",
      "data-hovered:bg-current/15 data-hovered:opacity-100 data-pressed:bg-current/25",
      "data-focus-visible:ring-2 data-focus-visible:ring-current",
    ],
  },
  variants: {
    color: { default: {}, success: {}, warning: {}, danger: {} },
    appearance: { soft: {}, solid: {}, outline: {} },
    size: {
      sm: {
        list: "gap-1.5",
        tag: "h-6 px-2 text-xs",
        remove: "size-4 [&_svg]:size-2.5",
      },
      md: {
        list: "gap-2",
        tag: "h-7 px-2.5 text-sm",
        remove: "size-4.5 [&_svg]:size-3",
      },
      lg: {
        list: "gap-2.5",
        tag: "h-9 px-3.5 text-sm",
        remove: "size-5 [&_svg]:size-3.5",
      },
    },
    shape: {
      rounded: { tag: "rounded-lg" },
      pill: { tag: "rounded-full" },
    },
  },
  compoundVariants: [
    // Solid
    { appearance: "solid", color: "default", class: { tag: "bg-fg text-bg" } },
    {
      appearance: "solid",
      color: "success",
      class: { tag: "bg-success text-success-fg" },
    },
    {
      appearance: "solid",
      color: "warning",
      class: { tag: "bg-warning text-warning-fg" },
    },
    {
      appearance: "solid",
      color: "danger",
      class: { tag: "bg-danger text-danger-fg" },
    },
    // Soft
    {
      appearance: "soft",
      color: "default",
      class: { tag: "bg-muted text-fg ring-1 ring-border ring-inset" },
    },
    {
      appearance: "soft",
      color: "success",
      class: { tag: "bg-success/12 text-success" },
    },
    {
      appearance: "soft",
      color: "warning",
      class: {
        tag: "bg-warning/20 text-[color-mix(in_oklab,var(--warning)_55%,var(--fg))]",
      },
    },
    {
      appearance: "soft",
      color: "danger",
      class: { tag: "bg-danger/12 text-danger" },
    },
    // Outline
    {
      appearance: "outline",
      color: "default",
      class: { tag: "border bg-transparent text-fg" },
    },
    {
      appearance: "outline",
      color: "success",
      class: { tag: "border border-success/50 bg-transparent text-success" },
    },
    {
      appearance: "outline",
      color: "warning",
      class: {
        tag: "border border-warning/60 bg-transparent text-[color-mix(in_oklab,var(--warning)_55%,var(--fg))]",
      },
    },
    {
      appearance: "outline",
      color: "danger",
      class: { tag: "border border-danger/50 bg-transparent text-danger" },
    },
  ],
  defaultVariants: {
    color: "default",
    appearance: "soft",
    size: "md",
    shape: "rounded",
  },
});

2. Add the Tag Group file

src/components/ui/tag-group/tag-group.tsxShow code
"use client";

import {
  createContext,
  type ReactElement,
  type ReactNode,
  useContext,
} from "react";
import {
  Button as AriaButton,
  Tag as AriaTag,
  TagGroup as AriaTagGroup,
  type TagGroupProps as AriaTagGroupProps,
  type TagProps as AriaTagProps,
  Label,
  TagList,
  Text,
} from "react-aria-components";
import { XIcon } from "@/components/icons";
import { Avatar, type AvatarProps } from "@/components/ui/avatar/avatar";
import { cn } from "@/lib/cn";
import { tagGroupStyles } from "@/types/tag-group-styles";

interface GroupContext {
  appearance: "soft" | "solid" | "outline";
  size: "sm" | "md" | "lg";
  shape: "rounded" | "pill";
}

const GroupContext = createContext<GroupContext>({
  appearance: "soft",
  size: "md",
  shape: "rounded",
});

export interface TagGroupProps<T extends object>
  extends Omit<
    AriaTagGroupProps,
    "children" | "className" | "style" | "aria-label"
  > {
  /** A label above the tags, which also names the group for screen readers. Without one, name it with `aria-label`. */
  label?: ReactNode;
  /** A line that says more, under the tags. */
  description?: ReactNode;
  /** A line under the tags in red, for what is wrong with the choice. */
  errorMessage?: ReactNode;
  /** Names the group for screen readers when there is no `label`. */
  "aria-label"?: string;
  /** How the tags are colored: a soft tint, a solid fill, or an outline. Defaults to `soft`. */
  appearance?: "soft" | "solid" | "outline";
  /** How big the tags are. Defaults to `md`. */
  size?: "sm" | "md" | "lg";
  /** Rounded corners, or a full pill. Defaults to `rounded`. */
  shape?: "rounded" | "pill";
  /** The tags, as data, for a group that changes. Use it with a function as the children. */
  items?: Iterable<T>;
  /** What it says when there are no tags. Defaults to "No tags." */
  emptyMessage?: ReactNode;
  /** `TagGroupItem`s, or a function that makes one from each of `items`. */
  children: ReactNode | ((item: T) => ReactElement);
  className?: string;
}

/**
 * A group of tags: short labels for what a thing is about (topics, filters,
 * people, statuses), that can be chosen, removed, or opened as links. Use it
 * where a tag is something to work with. To show a status that is not
 * interactive, use a Badge, and to type new tags into a field, a Tag Field.
 *
 * Built on react-aria's TagGroup: the arrow keys move between the tags, Space
 * chooses one, Backspace or Delete removes one that can be removed, and a screen
 * reader hears the group, each tag and whether it is chosen. A tag can be chosen
 * (one, several, or none), removed with `onRemove`, or be a link.
 *
 * Give each `TagGroupItem` an `id`, which is what the selection and `onRemove`
 * hold.
 *
 * @example
 * <TagGroup label="Topics" selectionMode="multiple">
 *   <TagGroupItem id="design">Design</TagGroupItem>
 *   <TagGroupItem id="code">Code</TagGroupItem>
 * </TagGroup>
 */
export function TagGroup<T extends object>({
  label,
  description,
  errorMessage,
  "aria-label": ariaLabel,
  appearance = "soft",
  size = "md",
  shape = "rounded",
  items,
  emptyMessage = "No tags.",
  children,
  className,
  ...props
}: TagGroupProps<T>) {
  const classes = tagGroupStyles({ size });

  return (
    <AriaTagGroup
      {...props}
      aria-label={label ? undefined : (ariaLabel ?? "Tags")}
      className={cn(classes.root(), className)}
    >
      {label ? <Label className={classes.label()}>{label}</Label> : null}
      <GroupContext.Provider value={{ appearance, size, shape }}>
        <TagList
          items={items}
          renderEmptyState={() => (
            <span className={classes.empty()}>{emptyMessage}</span>
          )}
          className={classes.list()}
        >
          {children}
        </TagList>
      </GroupContext.Provider>
      {description ? (
        <Text slot="description" className={classes.description()}>
          {description}
        </Text>
      ) : null}
      {errorMessage ? (
        <Text slot="errorMessage" className={classes.error()}>
          {errorMessage}
        </Text>
      ) : null}
    </AriaTagGroup>
  );
}

export interface TagGroupItemProps
  extends Omit<AriaTagProps, "className" | "style"> {
  /** An icon before the label. */
  icon?: ReactNode;
  /** An avatar before the label. */
  avatar?: AvatarProps;
  /** The color of this tag: a neutral, or one of the states. Defaults to `default`. */
  color?: "default" | "success" | "warning" | "danger";
  className?: string;
}

/**
 * One tag. `id` is the key that the selection and `onRemove` use. Give it a
 * `textValue` when its children are not plain text, so that a screen reader and
 * typing a letter have something to go by. With `href` it is a link.
 */
export function TagGroupItem({
  icon,
  avatar,
  color = "default",
  className,
  children,
  textValue,
  ...props
}: TagGroupItemProps) {
  const { appearance, size, shape } = useContext(GroupContext);
  const classes = tagGroupStyles({ color, appearance, size, shape });
  const name =
    textValue ?? (typeof children === "string" ? children : undefined);

  return (
    <AriaTag
      {...props}
      textValue={name}
      className={({ selectionMode }) =>
        cn(
          classes.tag(),
          selectionMode !== "none" && "cursor-pointer",
          className,
        )
      }
    >
      {(renderProps) => (
        <>
          {avatar ? (
            <Avatar size="xs" {...avatar} />
          ) : icon ? (
            <span aria-hidden="true" className={classes.icon()}>
              {icon}
            </span>
          ) : null}
          <span className={classes.label_()}>
            {typeof children === "function" ? children(renderProps) : children}
          </span>
          {renderProps.allowsRemoving ? (
            <AriaButton
              slot="remove"
              aria-label={name ? `Remove ${name}` : "Remove"}
              className={classes.remove()}
            >
              <XIcon />
            </AriaButton>
          ) : null}
        </>
      )}
    </AriaTag>
  );
}

3. Use it

import { TagGroup, TagGroupItem } from "@/components/ui/tag-group/tag-group";

Anatomy

A group of tags, and if you like a label and lines of text.

<TagGroup
  label="Topics"
  description="Pick the ones that fit."
  selectionMode="multiple"
  onRemove={(keys) => remove(keys)}
>
  <TagGroupItem id="design" icon={<StarIcon />}>Design</TagGroupItem>
  <TagGroupItem id="code" color="success">Code</TagGroupItem>
</TagGroup>
PartRendered asNotes
LabelspanAbove the tags. It also names the group for a screen reader.
TagGroupgridThe group. It has the focus, and the arrow keys move between tags.
TagGroupItemrowOne tag: an icon or avatar, a label, and a button to remove it when the group allows removing.
Description, errorpA line under the tags that says more, and one in red for what is wrong.

Keyboard

KeyWhat it does
TabMoves into the group, and out of it.
← → ↑ ↓Moves to the next or the previous tag.
SpaceChooses the tag, in a group that can choose.
EnterFollows the link of a tag, or chooses it.
Backspace, DeleteRemoves the tag, when the group has onRemove.
Shift + arrowIn a group of several, extends the choice.
Ctrl or ⌘ + AIn a group of several, chooses all.
EscapeClears the choice, in a group of several.

Examples

Usage

Each tag needs an id.

Design
Code
Research

One tag

selectionMode single. disallowEmptySelection keeps one tag chosen.

Category
Design
Code
Research
Writing
Product

Selected: code

Several tags

selectionMode multiple. A chosen tag is filled with the primary color.

Topics
Design
Code
Research
Writing
Product

Selected: design, research

Removable

onRemove gives each tag a button, and is called with the keys of the tags to take away.

Your topics
Design
Code
Research
Writing
Product
Press Backspace or Delete on a tag to remove it.

Filters

Choosable and removable together, and each tag with its own color.

Status: Open
Label: Bug
Assignee: Me

Chosen: none

Colors and appearance

color is on each tag, and appearance on the group.

Default
Success
Warning
Danger
Default
Success
Warning
Danger
Default
Success
Warning
Danger

Sizes

Alpha
Beta
Gamma
Alpha
Beta
Gamma
Alpha
Beta
Gamma

Shapes

Alpha
Beta
Gamma
Alpha
Beta
Gamma

Icons and avatars

Starred
Saved
Alerts
Ada
Alan

Disabled

Free
Pro
Team

Description and error

A line under the tags that says more, and one in red for what is wrong.

Notify me about
Replies
Mentions
News
You can change this later.
Notify me about
Replies
Mentions
Pick at least one.

Component API

TagGroup takes these props, and each TagGroupItem the second table.

TagGroup

PropTypeDefault
labelReactNode-
descriptionReactNode-
errorMessageReactNode-
aria-labelstring"Tags"
itemsIterable<T>-
selectionMode"none" | "single" | "multiple""none"
selectedKeys"all" | Iterable<Key>-
defaultSelectedKeys"all" | Iterable<Key>-
onSelectionChange(keys: Selection) => void-
disallowEmptySelectionbooleanfalse
disabledKeysIterable<Key>-
onRemove(keys: Set<Key>) => void-
appearance"soft" | "solid" | "outline""soft"
size"sm" | "md" | "lg""md"
shape"rounded" | "pill""rounded"
emptyMessageReactNode"No tags."
classNamestring-

TagGroupItem

PropTypeDefault
idKey-
childrenReactNode-
textValuestringthe label
iconReactNode-
avatarAvatarProps-
color"default" | "success" | "warning" | "danger""default"
hrefstring-
isDisabledbooleanfalse