Multi Select
SavePick several options as removable chips, with type-ahead filtering, a selection limit, and a tag mode that adds new values, where chips scale in and the rest slide aside.
- Category
- Forms
- Version
- 0.1.0
- Frameworks
- Next.js, Vite + React
- Styling
- Tailwind CSS v4
Preview
Multi Select preview
Amara Okafor
Priya Raman
Two approvals are required to merge.
regression
agent-runtime
Press Enter or comma to add a new label.
Installation
npx @shakenui/cli add multi-selectReview the plan first. A dry run lists every file and package without changing anything:
npx @shakenui/cli add multi-select --dry-runUsage
multi-select-example.tsx
"use client";
import { useState } from "react";
import { MultiSelect, type MultiSelectOption } from "@/components/shaken/ui/multi-select";
function Initials({ name }: { name: string }) {
const letters = name
.split(" ")
.map((part) => part[0])
.join("")
.slice(0, 2);
return (
<span className="flex size-4 items-center justify-center rounded-full bg-zinc-950/[0.08] text-[8px] font-semibold text-zinc-700 dark:bg-white/15 dark:text-zinc-200">
{letters}
</span>
);
}
const people = [
{ name: "Amara Okafor", role: "Platform" },
{ name: "Jonas Lindqvist", role: "Billing" },
{ name: "Priya Raman", role: "Security" },
{ name: "Tomรกs Herrera", role: "Platform" },
{ name: "Mei Tanaka", role: "Design" },
{ name: "Elif Demir", role: "Data" },
{ name: "Kwame Mensah", role: "Infra" },
];
const reviewers: MultiSelectOption[] = people.map((person) => ({
value: person.name.toLowerCase().replace(/\s+/g, "-"),
label: person.name,
description: person.role,
icon: <Initials name={person.name} />,
}));
const labels: MultiSelectOption[] = ["bug", "regression", "needs-repro", "billing", "agent-runtime", "docs", "good first issue"].map((label) => ({
value: label,
label,
}));
export default function MultiSelectExample() {
const [selected, setSelected] = useState(["amara-okafor", "priya-raman"]);
return (
<div className="grid w-full max-w-sm gap-6">
<MultiSelect
label="Reviewers"
options={reviewers}
value={selected}
onValueChange={setSelected}
max={3}
placeholder="Add reviewers"
description="Two approvals are required to merge."
/>
<MultiSelect
label="Labels"
options={labels}
defaultValue={["regression", "agent-runtime"]}
creatable
placeholder="Type to add a label"
description="Press Enter or comma to add a new label."
/>
</div>
);
}API
| Prop | Type | Default | Description |
|---|---|---|---|
| options | { value, label, description?, icon?, disabled? }[] | โ | The options to pick from. |
| value / defaultValue | string[] | โ | Selected values, in the order they were picked. |
| onValueChange | (value: string[]) => void | โ | Called with the new selection. |
| creatable | boolean | false | Tag mode: a value that is not in the list can be added with Enter, a comma, or the Add row. |
| max | number | โ | Most values that can be picked. Shows a count and disables the rest once full. |
| placeholder | string | "Selectโฆ" | Shown while nothing is selected. |
| emptyMessage | ReactNode | "No matches" | Shown when the query matches nothing. |
| name | string | โ | Submits each value under this name in a form. |
| label / description / error | ReactNode | โ | Label, helper text, and an error that marks the field invalid. |
Accessibility
- Built on Base UI Combobox in multiple mode: the input is role="combobox" with a listbox of options; arrow keys move the highlight and Enter toggles an option.
- Backspace at the start of the input removes the last chip; Left Arrow moves onto the chips, and each chip has a remove button labeled Remove <name>.
- The input describes how many are selected, the limit when there is one, and how to reach the chips.
- Escape closes the list and clears the query without dropping the selection.
- Chips scale in and siblings slide with transforms only; with reduced motion preferred they appear and leave in place.
Files
Installed into src/components/shaken, or components/shaken when the project has no src directory.
src/components/shaken/ui/multi-select.tsxmulti-select- npm packages: @base-ui/react@^1.9.0, motion@^14.14.0React and Tailwind CSS v4 required
Source
The exact source the CLI installs, from /r/items/react/multi-select/0.1.0.json.
ui/multi-select.tsxShowHide
ui/multi-select.tsx
"use client";
import { Combobox } from "@base-ui/react/combobox";
import { AnimatePresence, MotionConfig, motion } from "motion/react";
import { type KeyboardEvent, type ReactNode, useId, useMemo, useState } from "react";
function cx(...classes: (string | false | null | undefined)[]) {
return classes.filter(Boolean).join(" ");
}
export interface MultiSelectOption {
/** Stored in the value array. Must be unique. */
value: string;
/** Shown in the list and on the chip. */
label: string;
/** Secondary text at the end of the row, such as a role or a count. */
description?: string;
/** A 16px icon or avatar shown in the row and on the chip. */
icon?: ReactNode;
/** Shown but cannot be picked. */
disabled?: boolean;
}
interface ViewItem extends MultiSelectOption {
/** Set on the synthetic "Create" row in creatable mode. */
create?: boolean;
}
export interface MultiSelectProps {
/** The options to pick from. */
options: MultiSelectOption[];
/** The selected values. Pass with `onValueChange` to control them. */
value?: string[];
/** The starting selection when uncontrolled. */
defaultValue?: string[];
/** Called with the new selection, in the order it was picked. */
onValueChange?: (value: string[]) => void;
/** Visible label. Pass `aria-label` instead when the label is shown elsewhere. */
label?: ReactNode;
/** Names the field for screen readers when there is no visible label. */
"aria-label"?: string;
/** Helper text below the field. */
description?: ReactNode;
/** Error message. Marks the field invalid and replaces the description. */
error?: ReactNode;
/** Shown while nothing is selected. */
placeholder?: string;
/** Tag input mode: typing a value that is not in the list offers to add it. Enter or a comma adds it. */
creatable?: boolean;
/** The most values that can be picked. Further options are disabled until one is removed. */
max?: number;
/** Shown when nothing matches the query. */
emptyMessage?: ReactNode;
/** Submits each value under this name inside a form. */
name?: string;
disabled?: boolean;
required?: boolean;
id?: string;
/** Classes for the wrapping element. */
className?: string;
}
const spring = { type: "spring", duration: 0.32, bounce: 0 } as const;
function RemoveIcon() {
return (
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none">
<path d="M5 5l6 6M11 5l-6 6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
</svg>
);
}
function ChevronIcon() {
return (
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none">
<path d="M5.5 6.25L8 3.75l2.5 2.5M5.5 9.75L8 12.25l2.5-2.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
</svg>
);
}
const iconButton = cx(
"flex size-7 shrink-0 cursor-default items-center justify-center rounded-md text-zinc-400 dark:text-zinc-500",
"hover:bg-zinc-950/[0.04] hover:text-zinc-700 dark:hover:bg-white/[0.06] dark:hover:text-zinc-200",
"transition-colors duration-150 ease-out motion-reduce:transition-none",
"focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500 [&_svg]:size-4",
);
/**
* Picks several options, shown as removable chips in the field. Typing filters the list; arrow
* keys move through options, Left Arrow moves onto the chips, and Backspace removes the last one.
* Chips scale in where they land and the rest slide aside, so the field never jumps. Set
* `creatable` for a tag input and `max` to cap the selection.
*/
export function MultiSelect({
options,
value: valueProp,
defaultValue = [],
onValueChange,
label,
"aria-label": ariaLabel,
description,
error,
placeholder = "Selectโฆ",
creatable = false,
max,
emptyMessage = "No matches",
name,
disabled,
required,
id,
className,
}: MultiSelectProps) {
const generatedId = useId();
const inputId = id ?? generatedId;
const messageId = `${inputId}-message`;
const invalid = error != null && error !== false;
const message = invalid ? error : description;
const [innerValue, setInnerValue] = useState<string[]>(defaultValue);
const values = valueProp ?? innerValue;
const [created, setCreated] = useState<MultiSelectOption[]>([]);
const [query, setQuery] = useState("");
const known = useMemo(() => {
const map = new Map<string, MultiSelectOption>();
for (const option of [...options, ...created]) map.set(option.value, option);
return map;
}, [options, created]);
const selected = values.map((value) => known.get(value) ?? { value, label: value });
const full = max != null && values.length >= max;
const trimmed = query.trim();
const exact = trimmed ? [...known.values()].find((option) => option.label.toLocaleLowerCase() === trimmed.toLocaleLowerCase()) : undefined;
const items: ViewItem[] = [...options, ...created.filter((option) => !options.some((o) => o.value === option.value))];
if (creatable && trimmed && !exact && !full) items.push({ value: trimmed, label: trimmed, create: true });
function commit(next: string[]) {
if (valueProp === undefined) setInnerValue(next);
onValueChange?.(next);
}
function add(text: string) {
const option = exact ?? { value: text, label: text };
if (!exact) setCreated((list) => [...list, option]);
if (!values.includes(option.value) && !full) commit([...values, option.value]);
setQuery("");
}
function handleKeyDown(event: KeyboardEvent<HTMLInputElement>) {
if (creatable && event.key === "," && trimmed) {
event.preventDefault();
add(trimmed);
}
}
return (
<MotionConfig reducedMotion="user">
<Combobox.Root<ViewItem, true>
items={items}
multiple
value={selected}
onValueChange={(next, details) => {
// Escape on a closed list would wipe every chip; in a multi-select it only clears the query.
if (details.reason === "escape-key") {
setQuery("");
return;
}
const creation = next.find((item) => item.create);
if (creation) {
add(creation.label);
return;
}
commit(next.map((item) => item.value));
setQuery("");
}}
inputValue={query}
onInputValueChange={setQuery}
isItemEqualToValue={(item, current) => item.value === current.value}
itemToStringLabel={(item) => item.label}
itemToStringValue={(item) => item.value}
autoHighlight
name={name}
disabled={disabled}
required={required}
>
<div className={cx("grid gap-1.5", className)}>
{label || max != null ? (
<div className="flex items-baseline justify-between gap-3">
{label ? (
<label htmlFor={inputId} className="text-sm font-medium text-zinc-900 dark:text-zinc-100">
{label}
</label>
) : (
<span />
)}
{max != null ? (
<span aria-hidden="true" className={cx("font-mono text-xs tabular-nums", full ? "text-zinc-950 dark:text-white" : "text-zinc-500")}>
{values.length}/{max}
</span>
) : null}
</div>
) : null}
<Combobox.InputGroup
className={cx(
"relative flex min-h-9 w-full cursor-text items-start gap-1 rounded-lg border bg-white py-1 pr-1 pl-1 text-sm shadow-[0_1px_2px_rgb(0_0_0/0.04)] dark:bg-black dark:shadow-none",
"transition-[border-color,box-shadow] duration-150 ease-out motion-reduce:transition-none",
invalid
? "border-red-500/60 focus-within:border-red-500 focus-within:ring-3 focus-within:ring-red-500/20"
: "border-zinc-950/15 hover:border-zinc-950/25 focus-within:border-sky-500 focus-within:ring-3 focus-within:ring-sky-500/20 dark:border-white/15 dark:hover:border-white/25 dark:focus-within:border-sky-500",
"data-[disabled]:cursor-not-allowed data-[disabled]:opacity-60",
)}
>
<Combobox.Chips
aria-label={selected.length > 0 ? `Selected${typeof label === "string" ? ` ${label.toLowerCase()}` : ""}` : undefined}
className="flex min-w-0 flex-1 flex-wrap items-center gap-1"
>
<AnimatePresence initial={false} mode="popLayout">
{selected.map((item) => (
<Combobox.Chip
key={item.value}
aria-label={item.label}
aria-description="Press Backspace or Delete to remove"
render={
<motion.div
layout="position"
initial={{ opacity: 0, scale: 0.85, filter: "blur(2px)" }}
animate={{ opacity: 1, scale: 1, filter: "blur(0px)" }}
exit={{ opacity: 0, scale: 0.85, filter: "blur(2px)", transition: { duration: 0.14, ease: "easeOut" } }}
transition={spring}
/>
}
className={cx(
"flex h-6.5 max-w-full cursor-default items-center gap-1.5 rounded-md pr-0.5 pl-2 text-[13px] leading-none outline-hidden",
"bg-zinc-950/[0.05] text-zinc-800 dark:bg-white/[0.08] dark:text-zinc-100",
"focus-within:bg-zinc-950/[0.1] focus-within:shadow-[inset_0_0_0_1px_rgb(9_9_11/0.25)] dark:focus-within:bg-white/[0.14] dark:focus-within:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.3)]",
"data-[highlighted]:bg-zinc-950/[0.1] dark:data-[highlighted]:bg-white/[0.14]",
item.icon != null && "pl-1",
)}
>
{item.icon != null ? (
<span aria-hidden="true" className="flex size-4 shrink-0 items-center justify-center [&_svg]:size-3.5">
{item.icon}
</span>
) : null}
<span className="truncate">{item.label}</span>
<Combobox.ChipRemove
aria-label={`Remove ${item.label}`}
className={cx(
"flex size-5 shrink-0 cursor-default items-center justify-center rounded-[5px] text-zinc-400 outline-hidden dark:text-zinc-500",
"hover:bg-zinc-950/[0.08] hover:text-zinc-900 dark:hover:bg-white/[0.12] dark:hover:text-white",
"transition-colors duration-150 ease-out motion-reduce:transition-none [&_svg]:size-3.5",
)}
>
<RemoveIcon />
</Combobox.ChipRemove>
</Combobox.Chip>
))}
<motion.span key="__input" layout="position" transition={spring} className={cx(
"flex flex-1",
// At rest the input tucks in after the last chip; it claims room for typing once focused.
selected.length > 0 ? "min-w-2 focus-within:min-w-20" : "min-w-20",
)}>
<Combobox.Input
id={inputId}
aria-label={label ? undefined : ariaLabel}
aria-invalid={invalid || undefined}
aria-describedby={message ? messageId : undefined}
aria-description={
selected.length > 0
? `${selected.length}${max != null ? ` of ${max}` : ""} selected. From the start of the input, press Left Arrow to move to the selected items.`
: max != null
? `Pick up to ${max}.`
: undefined
}
placeholder={selected.length > 0 ? undefined : placeholder}
onKeyDown={handleKeyDown}
className="h-6.5 w-full min-w-0 bg-transparent px-1.5 text-sm text-zinc-950 outline-hidden placeholder:text-zinc-400 disabled:cursor-not-allowed dark:text-white dark:placeholder:text-zinc-500"
/>
</motion.span>
</AnimatePresence>
</Combobox.Chips>
<div className="flex shrink-0 items-center self-start">
{selected.length > 0 ? (
<Combobox.Clear aria-label="Clear all" className={iconButton}>
<RemoveIcon />
</Combobox.Clear>
) : null}
<Combobox.Trigger aria-label="Show options" className={iconButton}>
<ChevronIcon />
</Combobox.Trigger>
</div>
</Combobox.InputGroup>
{message ? (
<p id={messageId} className={invalid ? "text-sm text-red-600 dark:text-red-400" : "text-sm text-zinc-500 dark:text-zinc-400"}>
{message}
</p>
) : null}
</div>
<Combobox.Portal>
<Combobox.Positioner side="bottom" align="start" sideOffset={6} className="z-50 outline-hidden">
<Combobox.Popup
className={cx(
"w-(--anchor-width) max-w-(--available-width) origin-(--transform-origin) overflow-hidden rounded-xl outline-hidden",
"border border-zinc-950/10 bg-white text-zinc-950 shadow-[0_12px_32px_-8px_rgb(0_0_0/0.18)]",
"dark:border-white/15 dark:bg-black dark:text-white dark:shadow-[0_16px_48px_-12px_rgb(0_0_0/1),inset_0_1px_0_rgb(255_255_255/0.08)]",
"transition-[opacity,scale] duration-160 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none",
"data-[starting-style]:opacity-0 motion-safe:data-[starting-style]:scale-96",
"data-[ending-style]:opacity-0 data-[ending-style]:duration-110 data-[ending-style]:ease-out motion-safe:data-[ending-style]:scale-98",
)}
>
{full ? (
<p className="border-b border-zinc-950/[0.07] px-3.5 py-2 text-xs text-zinc-500 dark:border-white/[0.08] dark:text-zinc-400">
{`You can pick up to ${max}. Remove one to choose another.`}
</p>
) : null}
<Combobox.Empty className="px-3 py-6 text-center text-sm text-zinc-500 empty:m-0 empty:p-0 dark:text-zinc-400">
{emptyMessage}
</Combobox.Empty>
<Combobox.List className="max-h-[min(var(--available-height),18rem)] scroll-py-1.5 overflow-y-auto overscroll-contain p-1.5 outline-hidden data-[empty]:p-0">
{(item: ViewItem) => {
const isSelected = values.includes(item.value);
return (
<Combobox.Item
key={item.create ? `create:${item.value}` : item.value}
value={item}
disabled={item.disabled || (full && !isSelected)}
className={cx(
"group/option relative flex h-8 cursor-default items-center gap-2.5 rounded-md px-2 text-sm outline-hidden select-none",
"text-zinc-700 data-[highlighted]:bg-zinc-950/[0.05] data-[highlighted]:text-zinc-950",
"dark:text-zinc-300 dark:data-[highlighted]:bg-white/[0.08] dark:data-[highlighted]:text-white",
"data-[selected]:text-zinc-950 dark:data-[selected]:text-white",
"data-[disabled]:pointer-events-none data-[disabled]:opacity-45",
)}
>
{item.create ? (
<>
<span aria-hidden="true" className="flex size-4 shrink-0 items-center justify-center text-zinc-500">
<svg viewBox="0 0 16 16" fill="none" className="size-4">
<path d="M8 3.5v9M3.5 8h9" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
</svg>
</span>
<span className="min-w-0 flex-1 truncate">
Add <span className="font-medium text-zinc-950 dark:text-white">{`โ${item.label}โ`}</span>
</span>
<span className="shrink-0 text-xs text-zinc-400 dark:text-zinc-500">Enter</span>
</>
) : (
<>
{/* A check box that fills when the option is picked. */}
<span
aria-hidden="true"
className={cx(
"flex size-4 shrink-0 items-center justify-center rounded-[4px] border",
"border-zinc-950/20 text-white dark:border-white/25 dark:text-black",
"transition-[background-color,border-color] duration-150 ease-out motion-reduce:transition-none",
"group-data-[selected]/option:border-zinc-950 group-data-[selected]/option:bg-zinc-950 dark:group-data-[selected]/option:border-white dark:group-data-[selected]/option:bg-white",
)}
>
<svg viewBox="0 0 16 16" fill="none" className="size-3">
<path
d="M3.5 8.5l3 3 6-7"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
pathLength={1}
strokeDasharray="1"
className="[stroke-dashoffset:1] transition-[stroke-dashoffset] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] group-data-[selected]/option:[stroke-dashoffset:0] motion-reduce:transition-none"
/>
</svg>
</span>
{item.icon != null ? (
<span aria-hidden="true" className="flex size-4 shrink-0 items-center justify-center text-zinc-500 [&_svg]:size-4">
{item.icon}
</span>
) : null}
<span className="min-w-0 flex-1 truncate">{item.label}</span>
{item.description ? (
<span className="shrink-0 truncate text-xs text-zinc-400 dark:text-zinc-500">{item.description}</span>
) : null}
</>
)}
</Combobox.Item>
);
}}
</Combobox.List>
</Combobox.Popup>
</Combobox.Positioner>
</Combobox.Portal>
</Combobox.Root>
</MotionConfig>
);
}