Skip to content
Thrum

Tag

A chip for a filter, a recipient or a selection the reader can take away or switch on and off. A group wraps the tags and moves between them with the arrow keys. For a label nobody operates use the badge; for one pressed button use the toggle.

Install

npx shadcn@latest add https://thrumui.dev/r/tag.json

Adds components/ui/tag.tsx. Nothing else in your project changes.

import { Tag } from "@/components/ui/tag";

Automatically installs icon x from the icon set.

Props

PropTypeDefaultDescription
Tag: size"sm" | "md"Default "md"sm is 24 pixels tall with 12 pixel text, md is 28 pixels tall with 14 pixel text.
Tag: leadingReactNode–Something before the label: an icon, a dot, a small avatar. An SVG is sized to 14 pixels.
Tag: onRemove() => void–Makes the tag removable. It is called by the remove button and by Backspace or Delete on the tag. Take the tag out of your list here.
Tag: selectablebooleanDefault falseMakes the label a toggle button with aria-pressed, for a filter that can be on or off.
Tag: pressedboolean–Whether a selectable tag is pressed, when the parent holds the state. Use it with onPressedChange.
Tag: defaultPressedbooleanDefault falseWhether a selectable tag starts pressed, when it holds its own state.
Tag: onPressedChange(pressed: boolean) => void–Called with the new state when a selectable tag is pressed or released.
Tag: disabledbooleanDefault falseDimmed. Its buttons leave the tab order and cannot be pressed, and the keyboard cannot remove it.
Tag: soundbooleanDefault truePlay a short sound when the tag is removed, pressed or released, if the visitor has sound on.
Tag: childrenReactNode–The label. A long one is cut with an ellipsis at the width of the container; plain text is also its tooltip.
TagGroupComponentProps<"div">–A wrapping row with 6 pixels between tags. It has the group role: name it with aria-label.
classNamestring–On both parts: extra classes, merged last.

Motion and sound

Motion

  • Pressing a selectable tag changes its fill, border and text colour over 150 ms.
  • A removed tag leaves at once and the tags after it close the gap. Nothing slides.
  • Reduced motion: the colours change at once.

Sound

  • A low thud with a falling tone when a tag is removed.
  • Two rising clicks when a selectable tag is pressed, two falling clicks when it is released.

Sound is off until the visitor turns it on. Pass sound={false} to keep this component silent. How sound works

Accessibility

  • A plain tag is text in a span. A selectable tag holds a native button with aria-pressed, as the toggle button pattern asks.
  • The remove button is a native button named “Remove” plus the tag's label: “Remove Status: open”. It is 20 pixels wide with a 24 pixel target.
  • The group has the group role and is named by its aria-label. Arrow keys follow the reading direction, so they swap in right-to-left text.
  • In a group, when a focused tag is removed the focus moves to a neighbour. When the last one goes, focus rests on the group, not on the page.
  • Pressed and not pressed differ as a filled chip against an outlined one, and in aria-pressed.
KeysAction
TabFocus the next tag. Every tag that can be pressed or removed is a tab stop. On a tag that is both, Tab reaches its remove button after its label.
ArrowRight / ArrowDownIn a group, focus the next tag. It stops at the last one.
ArrowLeft / ArrowUpIn a group, focus the tag before. It stops at the first one.
Home / EndIn a group, focus the first or the last tag.
Space / EnterPress or release a selectable tag. On a remove button, remove the tag.
Backspace / DeleteRemove the focused tag. In a group, focus moves to the next tag, or to the one before when it was the last.

Source

components/ui/tag.tsx
"use client";

import { useId, useState, type ComponentProps, type ReactNode } from "react";

import { cn } from "@/lib/utils";
import { play } from "@/lib/thrum-sound";
import { XIcon } from "@/components/icons/x";

export type TagSize = "sm" | "md";

export type TagProps = ComponentProps<"span"> & {
  /** `sm` is 24 pixels tall, `md` is 28. */
  size?: TagSize;
  /** Something before the label: an icon, a dot, a small avatar. */
  leading?: ReactNode;
  /** Makes the tag removable: it gains a remove button, and Backspace or Delete on the tag calls this too. Take the tag out of your list here. */
  onRemove?: () => void;
  /** Makes the label a toggle button that stays pressed, for a filter that can be on or off. */
  selectable?: boolean;
  /** Whether a selectable tag is pressed, when the parent holds the state. Use it with `onPressedChange`. */
  pressed?: boolean;
  /** Whether a selectable tag starts pressed, when it holds its own state. */
  defaultPressed?: boolean;
  /** Called with the new state when a selectable tag is pressed or released. */
  onPressedChange?: (pressed: boolean) => void;
  /** Dimmed, and its buttons cannot be pressed. */
  disabled?: boolean;
  /** Play a short sound when the tag is removed, pressed or released, if the visitor has sound on. */
  sound?: boolean;
};

const SIZE: Record<TagSize, string> = { sm: "h-6 text-xs", md: "h-7 text-sm" };
const RING = "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring";
// Where focus lands in a tag: its toggle when it has one, otherwise its remove button.
const STOP = "[data-tag-stop]:not(:disabled)";

/**
 * A chip for a filter, a recipient, a selection. On its own it is a label. With `onRemove` it gains a remove button,
 * and with `selectable` its label becomes a toggle. Put several in a `TagGroup` for wrapping and arrow keys.
 */
export function Tag({
  size = "md",
  leading,
  onRemove,
  selectable = false,
  pressed: pressedProp,
  defaultPressed = false,
  onPressedChange,
  disabled = false,
  sound = true,
  className,
  children,
  onKeyDown,
  ...props
}: TagProps) {
  const id = useId();
  const [own, setOwn] = useState(defaultPressed);
  const pressed = selectable && (pressedProp ?? own);

  const remove = (tag: HTMLElement) => {
    // The tag is about to leave: hand the focus to the next tag, the one before, or the group.
    const group = tag.closest<HTMLElement>('[data-slot="tag-group"]');
    if (group && tag.contains(document.activeElement)) {
      const stops = [...group.querySelectorAll<HTMLElement>(STOP)];
      const at = stops.findIndex((stop) => tag.contains(stop));
      (stops[at + 1] ?? stops[at - 1] ?? group).focus();
    }
    if (sound) play("remove");
    onRemove?.();
  };

  const label = (
    <>
      {leading && (
        <span data-slot="tag-leading" className="inline-flex flex-none items-center [&_svg]:size-3.5">
          {leading}
        </span>
      )}
      <span id={`${id}-label`} className="truncate" title={typeof children === "string" ? children : undefined}>
        {children}
      </span>
    </>
  );
  const body = cn("inline-flex h-full min-w-0 items-center gap-1.5 ps-2", onRemove ? "pe-1" : "pe-2");

  return (
    <span
      data-slot="tag"
      data-surface={pressed ? "accent" : "control"}
      data-pressed={pressed ? "" : undefined}
      data-disabled={disabled ? "" : undefined}
      className={cn(
        "inline-flex max-w-full items-center rounded-sm border border-input bg-card font-medium whitespace-nowrap text-card-foreground",
        "transition-[background-color,border-color,color] duration-150 ease-out motion-reduce:transition-none",
        // Pressed is the primary fill with its own text colour: a filled chip against an empty one, not a tint of the same chip.
        "data-pressed:border-primary data-pressed:bg-primary data-pressed:text-primary-foreground data-disabled:opacity-65",
        SIZE[size],
        className,
      )}
      onKeyDown={(event) => {
        onKeyDown?.(event);
        if (event.defaultPrevented || !onRemove || disabled || (event.key !== "Backspace" && event.key !== "Delete")) return;
        event.preventDefault();
        remove(event.currentTarget);
      }}
      {...props}
    >
      {selectable ? (
        <button
          type="button"
          data-slot="tag-toggle"
          data-tag-stop=""
          aria-pressed={pressed}
          disabled={disabled}
          className={cn(body, "cursor-pointer rounded-sm hover:bg-current/10 disabled:cursor-not-allowed disabled:hover:bg-transparent", RING)}
          onClick={() => {
            if (sound) play(pressed ? "toggleOff" : "toggleOn");
            setOwn(!pressed);
            onPressedChange?.(!pressed);
          }}
        >
          {label}
        </button>
      ) : (
        <span className={body}>{label}</span>
      )}
      {onRemove && (
        <button
          type="button"
          id={`${id}-remove`}
          data-slot="tag-remove"
          data-tag-stop={selectable ? undefined : ""}
          // Named "Remove" plus the tag's own label, whatever the label is made of.
          aria-label="Remove"
          aria-labelledby={`${id}-remove ${id}-label`}
          disabled={disabled}
          // The button is 20 pixels; the pseudo-element makes its target 24.
          className={cn(
            "relative me-0.5 grid size-5 flex-none cursor-pointer place-items-center rounded-sm after:absolute after:-inset-0.5 hover:bg-current/10 disabled:cursor-not-allowed disabled:hover:bg-transparent",
            RING,
          )}
          onClick={(event) => remove(event.currentTarget.parentElement!)}
        >
          <XIcon size={14} />
        </button>
      )}
    </span>
  );
}

/**
 * A wrapping row of tags. It has the group role, so name it with `aria-label`.
 * Every tag stays a tab stop; the arrow keys, Home and End also move between them.
 */
export function TagGroup({ className, onKeyDown, ...props }: ComponentProps<"div">) {
  return (
    <div
      data-slot="tag-group"
      role="group"
      // Focusable from code only: when the last tag is removed, the focus rests here instead of falling to the page.
      tabIndex={-1}
      className={cn("flex max-w-full flex-wrap items-center gap-1.5 rounded-sm", RING, className)}
      onKeyDown={(event) => {
        onKeyDown?.(event);
        if (event.defaultPrevented) return;
        const group = event.currentTarget;
        const forward = getComputedStyle(group).direction === "rtl" ? "ArrowLeft" : "ArrowRight";
        const back = forward === "ArrowLeft" ? "ArrowRight" : "ArrowLeft";
        if (![forward, back, "ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return;
        const stops = [...group.querySelectorAll<HTMLElement>(STOP)];
        const tag = (event.target as HTMLElement).closest('[data-slot="tag"]');
        const at = stops.findIndex((stop) => tag?.contains(stop));
        if (at < 0) return;
        event.preventDefault();
        const to = event.key === "Home" ? 0 : event.key === "End" ? stops.length - 1 : event.key === forward || event.key === "ArrowDown" ? at + 1 : at - 1;
        stops[Math.max(0, Math.min(stops.length - 1, to))].focus();
      }}
      {...props}
    />
  );
}

Files and dependencies

Adds
components/ui/tag.tsx
Packages
None
Brings along
Sound engine
Icons
x

Changelog

  1. 1.0.0 · 2026-12-03First release.

Loading index…

Keyboard shortcuts

/Ctrl KSearch components, docs and actions
?Show this list
AAppearance studio
SSound on or off
MFull or reduced motion
TTheme: auto, light, dark
GSurface: solid or frosted
BBackdrop photograph (under glass)
CCorner radius: square to round
RReplay the demo, on a component page
DDraw new data, on a component page
←→HomeEndMove the cursor in a focused chart
EscClose a dialog, or leave a chart cursor