---
title: "Tags Input · UI SDK — StyleX Blocks"
description: "Enter-to-add token input with removable item previews in outline, subtle, and flushed styles."
url: "https://stylexblocks.com/components/ui-sdk/tags-input/"
agent:
  instructions: "Use this search API to find relevant components and blocks across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown."
  endpoint: "https://stylexblocks.com/.well-known/search?q={query}"
  method: "GET"
  documentation: "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/"
---

# Tags Input

Enter-to-add token input with removable item previews in outline, subtle, and flushed styles.

- Behavior engine: UI SDK
- Also available for: [Ark UI](https://stylexblocks.com/components/ark-ui/tags-input.md), [Base UI](https://stylexblocks.com/components/base-ui/tags-input.md)
- Category: Form
- Variants: outline, subtle, flushed
- Sizes: xs, sm, md, lg
- HTML page: https://stylexblocks.com/components/ui-sdk/tags-input/

## Install

Configure the project once (sets the behavior engine and import aliases):

```sh
npx stylexblocks init --style ui-sdk
```

Then add the item as source you own:

```sh
npx stylexblocks add tags-input
```

Equivalent: `npx shadcn add @stylexblocks/tags-input`. Registry item JSON: https://stylexblocks.com/r/ui-sdk/tags-input.json

## Usage

```tsx
import { TagsInput } from "#components/ui/ui-sdk/tags-input.tsx";

export function Example() {
  return (
    // the Input is one editor holding each tag as an atomic chip beside the
    // draft text: Enter adds, Backspace removes, undo/redo and paste work.
    // Chips render via renderItem (default: ItemPreview > ItemText + delete)
    <TagsInput.Root defaultValue={["Design", "Engineering"]} variant="outline" size="md">
      <TagsInput.Label>Teams</TagsInput.Label>
      <TagsInput.Control>
        <TagsInput.Input placeholder="Add team" aria-label="Teams" />
      </TagsInput.Control>
    </TagsInput.Root>
  );
}

// custom chips: <TagsInput.Root renderItem={(tag) => (
//   <TagsInput.ItemPreview><TagsInput.ItemText>#{tag}</TagsInput.ItemText></TagsInput.ItemPreview>
// )}>
```

## Source

`components/ui/ui-sdk/tags-input.tsx`

```tsx
import * as stylex from "@stylexjs/stylex";
import { createContext, useContext, useEffect, useMemo, useRef, useState } from "react";
import { mergeProps, renderElement, type PartProps } from "@ui-sdk/react/primitive";
import {
  createTokenInputController,
  TokenInput,
  TokenInputEditor,
  TokenInputToken,
  TokenInputTokenRemove,
  type Token,
  type TokenInputValue,
} from "@ui-sdk/react/token-input";
import { createSlotRecipeContext } from "#lib/ui-sdk/create-slot-recipe-context.tsx";
import {
  defineSlotRecipe,
  resolveSlotStyles,
  type SlotRecipeVariants,
} from "#lib/recipe-props.ts";
import {
  tagsInputItemDeleteTriggerIconVars,
  tagsInputClearTriggerIconVars,
} from '@stylexblocks/ui/slot-recipes/tags-input.stylex.ts'

import { colorPalette } from '@stylexblocks/ui/color-palette.stylex.ts'
import { durations } from '@stylexblocks/ui/tokens/durations.stylex.ts'
import { fontSizes } from '@stylexblocks/ui/tokens/font-sizes.stylex.ts'
import { fontWeights } from '@stylexblocks/ui/tokens/font-weights.stylex.ts'
import { lineHeights } from '@stylexblocks/ui/tokens/line-heights.stylex.ts'
import { semanticColors } from '@stylexblocks/ui/semantic-tokens/colors.stylex.ts'
import { semanticRadii } from '@stylexblocks/ui/semantic-tokens/radii.stylex.ts'
import { sizes } from '@stylexblocks/ui/tokens/sizes.stylex.ts'
import { spacing } from '@stylexblocks/ui/tokens/spacing.stylex.ts'


const tagsInputRoot = stylex.create({
  base: {
    display: 'flex',
    flexDirection: 'column',
    gap: spacing._1_5,
    width: sizes.full,
  },
})

const tagsInputRootSizes = stylex.create({
  xs: {
    '--tags-input-height': sizes._8,
    '--tags-input-px': spacing._1_5,
    '--tags-input-py': spacing._1,
    '--tags-input-gap': spacing._1,
    '--tags-input-item-height': sizes._6,
    '--tags-input-item-px': spacing._2,
    fontSize: fontSizes.xs,
    lineHeight: lineHeights.xs,
  },
  sm: {
    '--tags-input-height': sizes._9,
    '--tags-input-px': spacing._1_5,
    '--tags-input-py': spacing._1,
    '--tags-input-gap': spacing._1,
    '--tags-input-item-height': sizes._6,
    '--tags-input-item-px': spacing._2,
    fontSize: fontSizes.sm,
    lineHeight: lineHeights.sm,
  },
  md: {
    '--tags-input-height': sizes._10,
    '--tags-input-px': spacing._1_5,
    '--tags-input-py': spacing._1,
    '--tags-input-gap': spacing._1,
    '--tags-input-item-height': sizes._7,
    '--tags-input-item-px': spacing._2,
    fontSize: fontSizes.sm,
    lineHeight: lineHeights.sm,
  },
  lg: {
    '--tags-input-height': sizes._10,
    '--tags-input-px': spacing._1_5,
    '--tags-input-py': spacing._1,
    '--tags-input-gap': spacing._1,
    '--tags-input-item-height': sizes._8,
    '--tags-input-item-px': spacing._2,
    fontSize: fontSizes.md,
    lineHeight: lineHeights.md,
  },
})

const tagsInputLabel = stylex.create({
  base: {
    fontWeight: fontWeights.medium,
    fontSize: fontSizes.sm,
    lineHeight: lineHeights.sm,
    opacity: {
      default: null,
      ':is(:disabled, [disabled], [data-disabled])': 0.5,
    },
  },
})

const tagsInputControl = stylex.create({
  base: {
    '--focus-color': colorPalette.focusRing,
    '--error-color': semanticColors.borderError,
    minHeight: 'var(--tags-input-height)',
    '--input-height': 'var(--tags-input-height)',
    paddingInline: 'var(--tags-input-px)',
    paddingBlock: 'var(--tags-input-py)',
    gap: 'var(--tags-input-gap)',
    display: 'flex',
    flexWrap: 'wrap',
    alignItems: 'center',
    borderRadius: semanticRadii.l2,
    position: 'relative',
    transitionProperty: 'border-color, box-shadow',
    transitionDuration: durations.moderate,
    opacity: {
      default: null,
      ':is(:disabled, [disabled], [data-disabled])': 0.5,
    },
    borderColor: {
      default: null,
      ':is([data-invalid], [aria-invalid="true"])': 'var(--error-color)',
    },
  },
})

const tagsInputControlVariants = stylex.create({
  outline: {
    borderWidth: '1px',
    backgroundColor: semanticColors.bg,
    outlineWidth: {
      default: null,
      ':focus': '1px',
    },
    outlineStyle: {
      default: null,
      ':focus': 'solid',
    },
    outlineColor: {
      default: null,
      ':focus': {
        default: 'var(--focus-color)',
        ':is([data-invalid], [aria-invalid="true"])': 'var(--error-color)',
      },
    },
    borderColor: {
      default: null,
      ':is([data-invalid], [aria-invalid="true"])': 'var(--error-color)',
      ':focus': {
        default: 'var(--focus-color)',
        ':is([data-invalid], [aria-invalid="true"])': 'var(--error-color)',
      },
    },
  },
  subtle: {
    backgroundColor: semanticColors.bgMuted,
    borderWidth: '1px',
    borderColor: {
      default: 'transparent',
      ':is([data-invalid], [aria-invalid="true"])': 'var(--error-color)',
      ':focus': {
        default: 'var(--focus-color)',
        ':is([data-invalid], [aria-invalid="true"])': 'var(--error-color)',
      },
    },
    outlineWidth: {
      default: null,
      ':focus': '1px',
    },
    outlineStyle: {
      default: null,
      ':focus': 'solid',
    },
    outlineColor: {
      default: null,
      ':focus': {
        default: 'var(--focus-color)',
        ':is([data-invalid], [aria-invalid="true"])': 'var(--error-color)',
      },
    },
  },
  flushed: {
    borderRadius: 0,
    paddingInline: 0,
    backgroundColor: 'transparent',
    borderBottomWidth: '1px',
    borderBottomColor: semanticColors.border,
    borderColor: {
      default: null,
      ':is([data-invalid], [aria-invalid="true"])': 'var(--error-color)',
      ':focus': 'var(--focus-color)',
    },
    boxShadow: {
      default: null,
      ':focus': '0px 1px 0px 0px var(--focus-color)',
    },
  },
})

const tagsInputInput = stylex.create({
  base: {
    flex: 1,
    minWidth: sizes._20,
    outline: 'none',
    backgroundColor: 'transparent',
    color: semanticColors.fg,
    paddingInline: 'calc(var(--tags-input-item-px) / 1.25)',
    height: 'var(--tags-input-item-height)',
    display: {
      default: null,
      ':is([data-readonly], [aria-readonly="true"], [readonly])': 'none',
    },
  },
})

const tagsInputItemText = stylex.create({
  base: {
    lineClamp: 1,
  },
})

const tagsInputItemInput = stylex.create({
  base: {
    outline: 'none',
    backgroundColor: 'transparent',
    minWidth: '2ch',
    color: 'inherit',
    paddingInline: 'var(--tags-input-item-px)',
    height: 'var(--tags-input-item-height)',
  },
})

const tagsInputItemPreview = stylex.create({
  base: {
    height: 'var(--tags-input-item-height)',
    userSelect: 'none',
    display: 'inline-flex',
    alignItems: 'center',
    gap: spacing._1,
    borderRadius: semanticRadii.l1,
    paddingInline: 'var(--tags-input-item-px)',
  },
})

const tagsInputItemPreviewVariants = stylex.create({
  outline: {
    backgroundColor: colorPalette.subtle,
  },
  subtle: {
    backgroundColor: semanticColors.bg,
    borderWidth: '1px',
  },
  flushed: {
    backgroundColor: colorPalette.subtle,
  },
})

const tagsInputItemDeleteTrigger = stylex.create({
  base: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    width: 'calc(var(--tags-input-item-height) / 1.5)',
    height: 'calc(var(--tags-input-item-height) / 1.5)',
    marginInlineEnd: `calc(${spacing._1} * -1)`,
    opacity: {
      default: 0.4,
      ':hover': 1,
    },
    [tagsInputItemDeleteTriggerIconVars.width]: '80%',
    [tagsInputItemDeleteTriggerIconVars.height]: '80%',
  },
})

const tagsInputItemDeleteTriggerIcon = stylex.create({
  base: {
    width: tagsInputItemDeleteTriggerIconVars.width,
    height: tagsInputItemDeleteTriggerIconVars.height,
  },
})

const tagsInputClearTrigger = stylex.create({
  base: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    width: 'calc(var(--tags-input-item-height) / 1.5)',
    height: 'calc(var(--tags-input-item-height) / 1.5)',
    color: semanticColors.fgMuted,
    outlineWidth: {
      default: null,
      ':focus-visible': 'var(--focus-ring-width, 0)',
    },
    outlineOffset: {
      default: null,
      ':focus-visible': '0px',
    },
    outlineStyle: {
      default: null,
      ':focus-visible': 'solid',
    },
    outlineColor: {
      default: null,
      ':focus-visible': colorPalette.focusRing,
    },
    focusRingWidth: '2px',
    borderRadius: semanticRadii.l1,
    [tagsInputClearTriggerIconVars.width]: sizes._5,
    [tagsInputClearTriggerIconVars.height]: sizes._5,
  },
})

const tagsInputClearTriggerIcon = stylex.create({
  base: {
    width: tagsInputClearTriggerIconVars.width,
    height: tagsInputClearTriggerIconVars.height,
  },
})

export type TagsInputSize = keyof typeof tagsInputRootSizes

export type TagsInputVariant = keyof typeof tagsInputControlVariants

const tagsInputRecipe = defineSlotRecipe({
  slots: {
    root: { styles: tagsInputRoot, sizes: tagsInputRootSizes },
    label: { styles: tagsInputLabel },
    control: { styles: tagsInputControl, variants: tagsInputControlVariants },
    input: { styles: tagsInputInput },
    itemText: { styles: tagsInputItemText },
    itemInput: { styles: tagsInputItemInput },
    itemPreview: { styles: tagsInputItemPreview, variants: tagsInputItemPreviewVariants },
    itemDeleteTrigger: { styles: tagsInputItemDeleteTrigger },
    clearTrigger: { styles: tagsInputClearTrigger },
  },
  defaultVariants: { size: "md", variant: "outline" },
});

const chrome = stylex.create({
  btnReset: {
    appearance: "none",
    backgroundColor: "transparent",
    borderWidth: 0,
    borderStyle: "none",
    padding: 0,
    margin: 0,
    fontFamily: "inherit",
    fontSize: "inherit",
    color: "inherit",
    cursor: "pointer",
    textAlign: "inherit",
  },
  // UI SDK's editor is one contenteditable that holds the chips inline with
  // the draft text, so it wraps them itself instead of the control doing it
  editor: {
    height: "auto",
    minHeight: "var(--tags-input-item-height)",
    lineHeight: "var(--tags-input-item-height)",
    paddingInline: 0,
    whiteSpace: "pre-wrap",
    overflowWrap: "anywhere",
    cursor: "text",
    "::before": {
      content: {
        default: null,
        "[data-empty]": "attr(aria-placeholder)",
      },
      color: semanticColors.fgSubtle,
      paddingInline: "calc(var(--tags-input-item-px) / 1.25)",
      pointerEvents: "none",
    },
  },
  // chips sit inline in the text flow; a little space keeps them apart
  chip: {
    verticalAlign: "middle",
    marginInlineEnd: "var(--tags-input-gap)",
    boxSizing: "border-box",
    lineHeight: "normal",
  },
  chipSelected: {
    outlineWidth: { default: null, "[data-selected]": "2px" },
    outlineStyle: { default: null, "[data-selected]": "solid" },
    outlineColor: { default: null, "[data-selected]": "var(--focus-color)" },
  },
});

// the recipe draws control focus with `:focus` (Ark focuses the control);
// UI SDK focuses the editor inside it
const focusFix = stylex.create({
  outline: {
    outlineWidth: { default: null, ":focus-within": "1px" },
    outlineStyle: { default: null, ":focus-within": "solid" },
    outlineColor: { default: null, ":focus-within": "var(--focus-color)" },
    borderColor: { default: null, ":focus-within": "var(--focus-color)" },
  },
  flushed: {
    borderColor: { default: null, ":focus-within": "var(--focus-color)" },
    boxShadow: { default: null, ":focus-within": "0px 1px 0px 0px var(--focus-color)" },
  },
});

function CloseIcon(props: React.ComponentProps<"svg">) {
  return (
    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true" {...props}>
      <path d="m4 4 8 8m0-8-8 8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
    </svg>
  );
}

export interface TagsInputContextValue {
  value: string[];
  addValue: (tag: string) => void;
  removeValue: (tag: string) => void;
  clear: () => void;
}

const TagsInputContext = createContext<TagsInputContextValue>({
  value: [],
  addValue: () => {},
  removeValue: () => {},
  clear: () => {},
});

const { withProvider, withContext } = createSlotRecipeContext(tagsInputRecipe);

export type TagsInputVariantProps = Partial<SlotRecipeVariants<typeof tagsInputRecipe>>;

const TAG = "tag";

function tagToken(tag: string): Token {
  return { type: TAG, value: tag, label: tag, id: `${TAG}:${tag}` };
}

function tagsOf(value: TokenInputValue): string[] {
  return value.flatMap((segment) => (typeof segment === "string" ? [] : [segment.value]));
}

function draftOf(value: TokenInputValue): string {
  return value.filter((segment): segment is string => typeof segment === "string").join("");
}

const sameTags = (a: string[], b: string[]) =>
  a.length === b.length && a.every((tag, i) => tag === b[i]);

function DefaultItem({ tag }: { tag: string }) {
  return (
    <ItemPreview>
      <ItemText>{tag}</ItemText>
      <ItemDeleteTrigger />
    </ItemPreview>
  );
}

type RootNodeProps = Omit<PartProps<"div">, "defaultValue" | "onChange"> & {
  value?: string[];
  defaultValue?: string[];
  onValueChange?: (value: string[]) => void;
  /** Renders each tag inside the editor. Defaults to ItemPreview + ItemText + ItemDeleteTrigger. */
  renderItem?: (tag: string) => React.ReactNode;
  /** Submits the tags (comma-separated) under this name. */
  name?: string;
  disabled?: boolean;
  readOnly?: boolean;
};

function RootNode({
  render,
  value,
  defaultValue,
  onValueChange,
  renderItem,
  name,
  disabled,
  readOnly,
  children,
  ...rest
}: RootNodeProps) {
  const [controller] = useState(createTokenInputController);
  const [inner, setInner] = useState<string[]>(defaultValue ?? []);
  const current = value ?? inner;
  const latest = useRef(current);
  latest.current = current;
  const [initial] = useState<TokenInputValue>(() => current.map(tagToken));

  function commit(next: string[]) {
    if (sameTags(next, latest.current)) return;
    latest.current = next;
    setInner(next);
    onValueChange?.(next);
  }

  // a controlled `value` from outside replaces the chips, keeping the draft
  useEffect(() => {
    if (value === undefined) return;
    const editorValue = controller.getValue();
    if (sameTags(tagsOf(editorValue), value)) return;
    const draft = draftOf(editorValue);
    controller.setValue([...value.map(tagToken), ...(draft ? [draft] : [])]);
  }, [controller, value]);

  const ctx = useMemo<TagsInputContextValue>(
    () => ({
      value: current,
      addValue: (tag) => {
        const trimmed = tag.trim();
        if (trimmed && !current.includes(trimmed)) controller.insert(tagToken(trimmed), { at: "end" });
      },
      removeValue: (tag) => controller.removeToken(tagToken(tag).id!),
      clear: () => controller.clear(),
    }),
    [controller, current],
  );

  const element = renderElement(
    "div",
    mergeProps({ children }, rest),
    render as never,
    {},
  );

  return (
    <TagsInputContext.Provider value={ctx}>
      <TokenInput
        controller={controller}
        defaultValue={initial}
        name={name}
        disabled={disabled}
        readOnly={readOnly}
        codec={{ format: (token) => token.value, parse: (text) => [text] }}
        onValueChange={(next) => commit(tagsOf(next))}
        // Enter turns the draft text into a tag (duplicates are dropped)
        onSubmit={(next) => {
          const tags = tagsOf(next);
          const draft = draftOf(next).trim();
          const added = draft && !tags.includes(draft) ? [...tags, draft] : tags;
          controller.setValue(added.map(tagToken));
          commit(added);
        }}
        renderToken={(token) =>
          renderItem ? renderItem(token.value) : <DefaultItem tag={token.value} />
        }
      >
        {element}
      </TokenInput>
    </TagsInputContext.Provider>
  );
}

const ItemPreview = withContext(
  TokenInputToken,
  (v) => [
    ...resolveSlotStyles(tagsInputRecipe.slots.itemPreview, v),
    chrome.chip,
    chrome.chipSelected,
  ],
  "TagsInputItemPreview",
);

const ItemText = withContext("span", "itemText", "TagsInputItemText");

const StyledItemDeleteTrigger = withContext(
  TokenInputTokenRemove,
  (v) => [chrome.btnReset, ...resolveSlotStyles(tagsInputRecipe.slots.itemDeleteTrigger, v)],
  "TagsInputItemDeleteTrigger",
);

function ItemDeleteTrigger(props: React.ComponentProps<typeof StyledItemDeleteTrigger>) {
  const { children, ...rest } = props;
  return (
    <StyledItemDeleteTrigger {...rest}>
      {children ?? <CloseIcon {...stylex.props(tagsInputItemDeleteTriggerIcon.base)} />}
    </StyledItemDeleteTrigger>
  );
}
ItemDeleteTrigger.displayName = "TagsInputItemDeleteTrigger";

const StyledControl = withContext(
  "div",
  (v) => [
    ...resolveSlotStyles(tagsInputRecipe.slots.control, v),
    v.variant === "flushed" ? focusFix.flushed : focusFix.outline,
  ],
  "TagsInputControl",
);

const Input = withContext(
  TokenInputEditor,
  (v) => [...resolveSlotStyles(tagsInputRecipe.slots.input, v), chrome.editor],
  "TagsInputInput",
);

function ClearTriggerNode({ render, children, onClick, ...rest }: PartProps<"button">) {
  const { clear, value } = useContext(TagsInputContext);
  return renderElement(
    "button",
    mergeProps(
      {
        type: "button" as const,
        "aria-label": "Clear tags",
        hidden: value.length === 0,
        onMouseDown: (event: React.MouseEvent) => event.preventDefault(),
        onClick: (event: React.MouseEvent<HTMLButtonElement>) => {
          onClick?.(event);
          clear();
        },
        children: children ?? <CloseIcon {...stylex.props(tagsInputClearTriggerIcon.base)} />,
      },
      rest,
    ),
    render as never,
    {},
  );
}

function Context({ children }: { children: (ctx: TagsInputContextValue) => React.ReactNode }) {
  return children(useContext(TagsInputContext));
}

/**
 * TagsInput — UI SDK's token-input primitive styled with the StyleX slot
 * recipe. The editor (`Input`) is one contenteditable that holds each tag
 * as an atomic chip next to the draft text: Enter turns the draft into a
 * tag, Backspace removes the chip before the caret, arrows step over chips,
 * and undo/redo and copy/paste keep chips intact. Chips render through
 * `renderItem` (default: ItemPreview > ItemText + ItemDeleteTrigger), not
 * as children. `<TagsInput.Root variant size>` resolves the recipe once;
 * every part inherits it through context.
 */
export const TagsInput = {
  Root: withProvider(RootNode, "root", "TagsInputRoot"),
  Label: withContext("span", "label", "TagsInputLabel"),
  Control: StyledControl,
  Input,
  ItemPreview,
  ItemText,
  ItemDeleteTrigger,
  ClearTrigger: withContext(
    ClearTriggerNode,
    (v) => [chrome.btnReset, ...resolveSlotStyles(tagsInputRecipe.slots.clearTrigger, v)],
    "TagsInputClearTrigger",
  ),
  Context,
};

export type TagsInputRootProps = React.ComponentProps<typeof TagsInput.Root>;
```
