---
title: "Listbox · UI SDK — StyleX Blocks"
description: "An always-visible option list with selection indicators in subtle and solid panels."
url: "https://stylexblocks.com/components/ui-sdk/listbox/"
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/"
---

# Listbox

An always-visible option list with selection indicators in subtle and solid panels.

- Behavior engine: UI SDK
- Also available for: [Ark UI](https://stylexblocks.com/components/ark-ui/listbox.md), [Base UI](https://stylexblocks.com/components/base-ui/listbox.md)
- Category: Form
- Variants: subtle, solid
- HTML page: https://stylexblocks.com/components/ui-sdk/listbox/

## 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 listbox
```

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

## Usage

```tsx
import { Listbox } from "#components/ui/ui-sdk/listbox.tsx";

const options = ["All activity", "Mentions only", "Weekly digest", "Muted"];

export function Example() {
  return (
    // Root holds the selection options (value/defaultValue/onValueChange,
    // multiple, disabled) and hands them to Content, UI SDK's listbox,
    // which the Label names; arrow keys and typeahead come from the engine
    <Listbox.Root defaultValue="Weekly digest" variant="subtle">
      <Listbox.Label>Notifications</Listbox.Label>
      <Listbox.Content>
        {options.map((option) => (
          <Listbox.Item key={option} value={option}>
            <Listbox.ItemText>{option}</Listbox.ItemText>
            <Listbox.ItemIndicator />
          </Listbox.Item>
        ))}
      </Listbox.Content>
    </Listbox.Root>
  );
}
```

## Source

`components/ui/ui-sdk/listbox.tsx`

```tsx
import * as stylex from "@stylexjs/stylex";
import { createContext, useContext, useEffect, useId, useMemo, useState } from "react";
import {
  Listbox as UiSdkListbox,
  ListboxGroup,
  ListboxGroupLabel,
  ListboxItem,
  ListboxItemIndicator,
  ListboxSeparator,
} from "@ui-sdk/react/listbox";
import { renderElement, type PartProps, type RenderProp } from "@ui-sdk/react/primitive";
import { createSlotRecipeContext } from "#lib/ui-sdk/create-slot-recipe-context.tsx";
import {
  defineSlotRecipe,
  resolveSlotStyles,
  type SlotRecipeVariants,
  type StyleOverrideProps,
} from "#lib/recipe-props.ts";
import { listboxItemIndicatorIconVars } from '@stylexblocks/ui/slot-recipes/listbox.stylex.ts'

import { cursor } from '@stylexblocks/ui/tokens/cursor.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 listboxRoot = stylex.create({
  base: {
    display: 'flex',
    flexDirection: 'column',
    gap: spacing._1_5,
    width: sizes.full,
  },
})

const listboxContent = stylex.create({
  base: {
    display: 'flex',
    flexDirection: 'column',
    overflowY: 'auto',
    maxHeight: sizes._96,
    padding: spacing._1,
    gap: spacing._1,
    fontSize: fontSizes.sm,
    lineHeight: lineHeights.sm,
    outline: 'none',
    scrollPadding: 1,
    '--listbox-item-padding-x': spacing._2,
    '--listbox-item-padding-y': spacing._1_5,
  },
})

const listboxContentVariants = stylex.create({
  subtle: {
    backgroundColor: semanticColors.bgPanel,
    borderWidth: '1px',
    borderRadius: semanticRadii.panelMd,
  },
  solid: {
    backgroundColor: semanticColors.bgPanel,
    borderWidth: '1px',
    borderRadius: semanticRadii.panelMd,
  },
})

const listboxItem = stylex.create({
  base: {
    position: 'relative',
    userSelect: 'none',
    display: 'flex',
    alignItems: 'center',
    gap: spacing._2,
    cursor: cursor.option,
    justifyContent: 'space-between',
    flex: 1,
    textAlign: 'start',
    borderRadius: semanticRadii.controlMd,
    paddingBlock: 'var(--listbox-item-padding-y)',
    paddingInline: 'var(--listbox-item-padding-x)',
    pointerEvents: {
      default: null,
      ':is(:disabled, [disabled], [data-disabled])': 'none',
    },
    opacity: {
      default: null,
      ':is(:disabled, [disabled], [data-disabled])': 0.5,
    },
  },
})

const listboxItemVariants = stylex.create({
  subtle: {
    backgroundColor: {
      default: null,
      ':hover': `color-mix(in oklch, ${semanticColors.bgEmphasized} 60%, transparent)`,
    },
  },
  solid: {},
})

const listboxEmpty = stylex.create({
  base: {
    paddingBlock: 'var(--listbox-item-padding-y)',
    paddingInline: 'var(--listbox-item-padding-x)',
  },
})

const listboxItemText = stylex.create({
  base: {
    flex: 1,
  },
})

const listboxItemGroup = stylex.create({
  base: {
    marginTop: {
      default: spacing._1_5,
      ':first-child': 0,
    },
  },
})

const listboxItemGroupLabel = stylex.create({
  base: {
    paddingBlock: spacing._1_5,
    paddingInline: spacing._2,
    fontWeight: fontWeights.medium,
  },
})

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

const listboxValueText = stylex.create({
  base: {
    lineClamp: 1,
    maxWidth: '80%',
  },
})

const listboxItemIndicator = stylex.create({
  base: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    [listboxItemIndicatorIconVars.width]: sizes._4,
    [listboxItemIndicatorIconVars.height]: sizes._4,
  },
})

const listboxItemIndicatorIcon = stylex.create({
  base: {
    width: listboxItemIndicatorIconVars.width,
    height: listboxItemIndicatorIconVars.height,
  },
})

export type ListboxVariant = keyof typeof listboxContentVariants

const listboxRecipe = defineSlotRecipe({
  slots: {
    root: { styles: listboxRoot },
    content: { styles: listboxContent, variants: listboxContentVariants },
    item: { styles: listboxItem, variants: listboxItemVariants },
    empty: { styles: listboxEmpty },
    itemText: { styles: listboxItemText },
    itemGroup: { styles: listboxItemGroup },
    itemGroupLabel: { styles: listboxItemGroupLabel },
    label: { styles: listboxLabel },
    valueText: { styles: listboxValueText },
    itemIndicator: { styles: listboxItemIndicator },
  },
  defaultVariants: { variant: "subtle" },
});

// UI SDK marks the chosen option with `data-selected` (the recipe leaves the
// selected fill to the composition layer).
const chrome = stylex.create({
  itemSelected: {
    backgroundColor: {
      default: null,
      ":is([data-selected])": semanticColors.bgMuted,
    },
  },
  separator: {
    height: "1px",
    marginBlock: spacing._1,
    backgroundColor: semanticColors.border,
  },
});

function CheckIcon(props: React.ComponentProps<"svg">) {
  return (
    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true" {...props}>
      <path d="m3.5 8.5 3 3 6-7" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

type ListboxValue = string | string[] | null;

/** Selection options Root takes and hands to the list (Content). */
interface ListboxOptions {
  value?: ListboxValue;
  defaultValue?: ListboxValue;
  onValueChange?: (value: never, details: never) => void;
  multiple?: boolean;
  activation?: "automatic" | "manual";
  deselectable?: boolean;
  orientation?: "horizontal" | "vertical";
  loop?: boolean;
  disabled?: boolean;
  readOnly?: boolean;
  required?: boolean;
  name?: string;
  form?: string;
}

const OPTION_KEYS = [
  "value",
  "defaultValue",
  "onValueChange",
  "multiple",
  "activation",
  "deselectable",
  "orientation",
  "loop",
  "disabled",
  "readOnly",
  "required",
  "name",
  "form",
] as const;

interface ListboxContextValue {
  options: ListboxOptions;
  labelId: string;
  hasLabel: boolean;
  setHasLabel: (has: boolean) => void;
}

const ListboxContext = createContext<ListboxContextValue>({
  options: {},
  labelId: "",
  hasLabel: false,
  setHasLabel: () => {},
});

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

export type ListboxVariantProps = Partial<SlotRecipeVariants<typeof listboxRecipe>>;

function RootNode(allProps: Omit<PartProps<"div">, keyof ListboxOptions> & ListboxOptions) {
  const { render, ...others } = allProps;
  const options: ListboxOptions = {};
  const rest: Record<string, unknown> = {};
  for (const [key, val] of Object.entries(others)) {
    if ((OPTION_KEYS as readonly string[]).includes(key)) {
      (options as Record<string, unknown>)[key] = val;
    } else {
      rest[key] = val;
    }
  }
  const labelId = useId();
  const [hasLabel, setHasLabel] = useState(false);
  const optionDeps = OPTION_KEYS.map((k) => options[k]);
  const ctx = useMemo<ListboxContextValue>(
    () => ({ options, labelId, hasLabel, setHasLabel }),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [labelId, hasLabel, ...optionDeps],
  );
  return (
    <ListboxContext.Provider value={ctx}>
      {renderElement("div", rest, render as RenderProp<object> | undefined, {})}
    </ListboxContext.Provider>
  );
}

function LabelNode(props: React.ComponentProps<"span">) {
  const { labelId, setHasLabel } = useContext(ListboxContext);
  useEffect(() => {
    setHasLabel(true);
    return () => setHasLabel(false);
  }, [setHasLabel]);
  return <span id={labelId} {...props} />;
}

function ContentNode(props: Omit<PartProps<"div">, keyof ListboxOptions>) {
  const { options, labelId, hasLabel } = useContext(ListboxContext);
  const labelled =
    hasLabel && props["aria-label"] === undefined && props["aria-labelledby"] === undefined;
  return (
    <UiSdkListbox
      {...(options as object)}
      aria-labelledby={labelled ? labelId : undefined}
      {...(props as object)}
    />
  );
}

const StyledItemIndicator = withContext(
  ListboxItemIndicator,
  "itemIndicator",
  "ListboxItemIndicator",
);

function ItemIndicator(
  props: Omit<React.ComponentProps<typeof ListboxItemIndicator>, "style"> & StyleOverrideProps,
) {
  const { children, ...rest } = props;
  return (
    <StyledItemIndicator {...rest}>
      {children ?? <CheckIcon {...stylex.props(listboxItemIndicatorIcon.base)} />}
    </StyledItemIndicator>
  );
}
ItemIndicator.displayName = "ListboxItemIndicator";

/**
 * Listbox — UI SDK's listbox wearing the listbox slot recipe: an
 * always-visible option list with arrow-key navigation, typeahead and (with
 * `multiple`) range selection. Root holds the selection options
 * (`value`/`defaultValue`/`onValueChange`, `multiple`, `disabled`, ...) and
 * hands them to Content, the engine's `role="listbox"` element, which a
 * `Label` names automatically. Selected items carry `data-selected`;
 * ItemIndicator renders a check icon by default and only appears on them.
 * `<Listbox.Root variant>` resolves the recipe once; every part inherits it
 * through context. Composition per part via `render`.
 */
export const Listbox = {
  Root: withProvider(RootNode, "root", "ListboxRoot"),
  Label: withContext(LabelNode, "label", "ListboxLabel"),
  Content: withContext(ContentNode, "content", "ListboxContent"),
  Item: withContext(
    ListboxItem,
    (v) => [...resolveSlotStyles(listboxRecipe.slots.item, v), chrome.itemSelected],
    "ListboxItem",
  ),
  ItemText: withContext("span", "itemText", "ListboxItemText"),
  ItemIndicator,
  ItemGroup: withContext(ListboxGroup, "itemGroup", "ListboxItemGroup"),
  ItemGroupLabel: withContext(ListboxGroupLabel, "itemGroupLabel", "ListboxItemGroupLabel"),
  Separator: withContext(ListboxSeparator, () => [chrome.separator], "ListboxSeparator"),
};

export type ListboxRootProps = React.ComponentProps<typeof Listbox.Root>;
export type ListboxItemProps = React.ComponentProps<typeof Listbox.Item>;
```
