Select
@codeui/solid v0.3.0
A button that opens a list of options and shows the chosen one.
When to use
Use Select when the user picks from a list of options they know by name, such as the editor font, the export format, or the pixel ratio. The list fits on screen without search.
When to choose another component
| Component | Use it when | The deciding difference |
|---|---|---|
Select | The user picks one or more values from a short list. | A button opens a list. No typing. |
| Combobox | The list is long enough that the user wants to search it. | A text input filters the list as the user types. |
| Listbox | The options stay visible on the page, such as a sidebar list. | No trigger and no popover. |
| CommandMenu | The user runs an action, such as Export as PNG. | A dialog that runs a command and keeps no value. |
| SegmentedControl | There are two to four short options. | All options are visible at once. |
Inkstone puts Select after segmented controls, switches, and option cards. Inside a modal dialog, prefer those controls over Select. See Choosing a control.
Live demo
import { createSignal } from "solid-js";
import { Select } from "@codeui/solid/select";
const fonts = ["JetBrains Mono", "Fira Code", "Source Code Pro", "Cascadia Code"];
export default function SelectBasicDemo() {
const [font, setFont] = createSignal("JetBrains Mono");
return (
<Select
aria-label="Font"
label="Font"
placeholder="Choose a font"
options={fonts}
value={font()}
onChange={value => value && setFont(value)}
/>
);
}Anatomy
Tap a part to outline it in the demo.
- 01Root
selectclasses.root - 02Label
select-labelclasses.label - 03Trigger
select-triggerclasses.trigger - 04Value
select-valueclasses.value - 05Icon
select-iconclasses.icon - 06Description
select-descriptionclasses.description - 07ErrorMessage
select-error-messageclasses.errorMessage - 08Content
select-contentclasses.content - 09Listbox
select-listboxclasses.listbox - 10Item
select-itemclasses.item - 11ItemLabel
select-item-labelclasses.itemLabel - 12ItemIndicator
select-item-indicatorclasses.itemIndicator
| Export | Renders | classes key | data-cui | Role |
|---|---|---|---|---|
Root | div | root | select | None |
Label | span | label | select-label | None |
Trigger | button | trigger | select-trigger | Button with aria-haspopup="listbox" |
Value | span | value | select-value | None |
Icon | span | icon | select-icon | None, hidden from assistive technology |
Description | div | description | select-description | None |
ErrorMessage | div | errorMessage | select-error-message | None |
Content | div, portalled | content | select-content | None |
Listbox | ul | listbox | select-listbox | Listbox |
Item | li | item | select-item | Option |
ItemLabel | div | itemLabel | select-item-label | None |
ItemIndicator | div | itemIndicator | select-item-indicator | None |
The label, description, and error message render only when you pass them. The list renders in a portal on document.body while it is open. With name, Select also renders one input type="hidden" for each selected value, with no data-cui marker and no classes key. See Submit with a form.
Variants
String options
The live demo passes a string[]. A string[] works as it is. Each string is the value, the label, and the type-ahead text.
Object options with createSelectOptions
import { createSignal } from "solid-js";
import { createSelectOptions, Select } from "@codeui/solid";
type Theme = { id: string; name: string };
const themes: Theme[] = [
{ id: "dracula", name: "Dracula" },
{ id: "one-dark", name: "One Dark" },
{ id: "night-owl", name: "Night Owl" },
{ id: "github-light", name: "GitHub Light" },
];
export default function SelectObjectOptionsDemo() {
const [themeId, setThemeId] = createSignal<string | undefined>("dracula");
const themeOptions = createSelectOptions(themes, { key: "name", valueKey: "id" });
return (
<Select
aria-label="Theme"
label="Theme"
placeholder="Choose a theme"
options={themeOptions.options()}
{...themeOptions.props()}
{...themeOptions.controlled(themeId, setThemeId)}
/>
);
}createSelectOptions maps your objects to { label, value } options. Spread props() for the keys and renderers. Spread controlled(value, setValue) to keep your own value, here the theme id, instead of the option object. See Options and collections for the full return value.
Object options without the helper
import { Select } from "@codeui/solid";
type Language = { extension: string; name: string };
const languages: Language[] = [
{ extension: "ts", name: "TypeScript" },
{ extension: "rs", name: "Rust" },
{ extension: "py", name: "Python" },
{ extension: "go", name: "Go" },
];
export default function SelectRawObjectsDemo() {
return (
<Select
aria-label="Language"
label="Language"
placeholder="Choose a language"
options={languages}
optionValue="extension"
optionTextValue="name"
itemLabel={language => language.name}
valueComponent={language => language().name}
defaultValue={languages[0]}
/>
);
}Without the helper, set optionValue and optionTextValue, and pass itemLabel and valueComponent. Select renders the raw option when you leave out the two renderers. An object then renders as nothing useful.
Disabled options
import { Select } from "@codeui/solid";
type Format = { id: string; name: string; available: boolean };
const formats: Format[] = [
{ id: "png", name: "PNG", available: true },
{ id: "svg", name: "SVG", available: true },
{ id: "pdf", name: "PDF (coming soon)", available: false },
{ id: "webp", name: "WebP", available: true },
];
export default function SelectDisabledOptionsDemo() {
return (
<Select
aria-label="Export format"
label="Export format"
options={formats}
optionValue="id"
optionTextValue="name"
optionDisabled={format => !format.available}
itemLabel={format => format.name}
valueComponent={format => format().name}
defaultValue={formats[0]}
/>
);
}optionDisabled takes a key or a function. Disabled options stay in the list, take no selection, and are skipped by the arrow keys. createSelectOptions has no disabled mapping. With the helper, pass optionDisabled as a function over the { label, value } option.
Filled and inline
import { Select } from "@codeui/solid";
const fonts = ["JetBrains Mono", "Fira Code", "Source Code Pro"];
export default function SelectThemesDemo() {
return (
<>
<Select aria-label="Font" label="Filled" options={fonts} defaultValue="Fira Code" variant="filled" />
<Select aria-label="Font" label="Inline" options={fonts} defaultValue="Fira Code" variant="inline" />
</>
);
}filled, the default, draws the field box. inline drops the box and keeps a bottom border, for a select that sits inside a sentence or a toolbar.
Sizes
import { For } from "solid-js";
import { Select } from "@codeui/solid";
const sizes = ["xs", "sm", "md", "lg"] as const;
const fonts = ["JetBrains Mono", "Fira Code", "Source Code Pro"];
export default function SelectSizesDemo() {
return (
<For each={sizes}>
{size => (
<Select
aria-label={`Font, size ${size}`}
label={`Size ${size}`}
options={fonts}
defaultValue="JetBrains Mono"
size={size}
/>
)}
</For>
);
}xs, sm, md, and lg are 28px, 36px, 44px, and 52px at comfortable density. The default is sm. The trigger uses at least 16px text at touch density and on touch devices. Options use the shared sm row height (32px compact, 36px comfortable, 40px touch).
Multiple selection
import { createSignal } from "solid-js";
import { Select } from "@codeui/solid";
const formats = ["PNG", "SVG", "JPEG", "WebP"];
export default function SelectMultipleDemo() {
const [selected, setSelected] = createSignal(["PNG", "SVG"]);
return (
<Select<string>
aria-label="Export formats"
label="Export formats"
placeholder="Choose formats"
description="Each format downloads as a separate file."
multiple
options={formats}
value={selected()}
onChange={values => setSelected(values)}
valueComponentMultiple={values => `${values().length} formats: ${values().join(", ")}`}
/>
);
}multiple makes value, defaultValue, and onChange work with arrays. The list stays open after each pick. The trigger joins the selected strings with ", ". Pass valueComponentMultiple for object options or for a summary such as a count. Pass the option type explicitly, as in <Select<string> multiple …>. Without it, TypeScript infers the option type from the array value.
Description
import { Select } from "@codeui/solid";
const scales = ["1x", "2x", "3x", "4x"];
export default function SelectDescriptionDemo() {
return (
<Select
aria-label="Pixel ratio"
label="Pixel ratio"
description="Higher ratios export sharper images and larger files."
options={scales}
defaultValue="2x"
/>
);
}description renders a hint under the trigger and links it as the accessible description.
States
Controlled and uncontrolled
import { Select } from "@codeui/solid";
const formats = ["PNG", "SVG", "JPEG", "WebP"];
export default function SelectUncontrolledDemo() {
return (
<Select
aria-label="Export format"
label="Export format"
options={formats}
defaultValue="PNG"
onChange={format => console.log("Export as", format)}
/>
);
}Pass value and onChange to own the value, as the live demo does. Pass defaultValue to let Select keep it. onChange receives null when the selection is cleared. Guard for it before you write the value back, as in value => value && setFont(value).
Disabled
import { Select } from "@codeui/solid";
export default function SelectDisabledDemo() {
return (
<Select
aria-label="Font"
label="Font"
options={["JetBrains Mono", "Fira Code"]}
defaultValue="JetBrains Mono"
disabled
/>
);
}disabled disables the trigger and removes it from the tab order.
Read only
import { Select } from "@codeui/solid";
export default function SelectReadOnlyDemo() {
return (
<Select
aria-label="Workspace theme"
label="Workspace theme"
description="Set by the workspace owner."
options={["Dracula", "One Dark", "Night Owl"]}
defaultValue="Dracula"
readOnly
/>
);
}readOnly keeps the trigger focusable and blocks changes. Use it for a value the user can see but someone else sets.
Invalid and required
import { Select } from "@codeui/solid";
export default function SelectInvalidDemo() {
return (
<Select
aria-label="Language"
label="Language"
placeholder="Choose a language"
options={["TypeScript", "Rust", "Python"]}
required
validationState="invalid"
errorMessage="Choose a language to highlight the snippet."
/>
);
}validationState="invalid" marks the trigger with aria-invalid and shows errorMessage. required marks the field as required for assistive technology. Select does not validate on its own. Set validationState from your form logic.
Empty
import { Select } from "@codeui/solid";
const presets: string[] = [];
export default function SelectEmptyDemo() {
return (
<Select
aria-label="Preset"
label="Preset"
placeholder="No saved presets"
description="Save a preset from the editor to list it here."
options={presets}
disabled={presets.length === 0}
/>
);
}Select has no empty-state prop. With no options, the list opens with nothing in it. Disable the trigger and explain why in the placeholder or the description, as the demo does.
Ready API
Select
Select renders a label, a trigger with the selected value, the messages, and a portalled list built on Kobalte's select.
Prop
Type
Import SelectProps and SelectClasses from @codeui/solid/select or @codeui/solid.
Inherited from Kobalte's select root:
Prop
Type
Style the list popover with classes
import { Select } from "@codeui/solid";
const fonts = ["JetBrains Mono", "Fira Code", "Source Code Pro", "Cascadia Code"];
export default function SelectClassesDemo() {
return (
<Select
aria-label="Font"
label="Font"
options={fonts}
defaultValue="Fira Code"
classes={{
root: "font-picker",
trigger: "font-picker-trigger",
content: "font-picker-list",
item: "font-picker-item",
}}
/>
);
}classes puts a class on any part in the anatomy table. classes.content reaches the portalled list, so you can size or position it without a global selector. The kit classes come first and your class comes after, so your rules win at equal specificity. slotClasses is deprecated. Its input, errorLabel, and itemValue keys map to trigger, errorMessage, and value.
Submit with a form
import { createSignal } from "solid-js";
import { Button, Select } from "@codeui/solid";
const formats = ["PNG", "SVG", "JPEG"];
export default function SelectFormDemo() {
const [submitted, setSubmitted] = createSignal<string>();
return (
<form
onSubmit={event => {
event.preventDefault();
const data = new FormData(event.currentTarget);
setSubmitted(String(data.get("format")));
}}
>
<Select label="Export format" name="format" options={formats} defaultValue="PNG" />
<Button variant="primary" type="submit">
Export
</Button>
<p>{submitted() ? `Submitted format=${submitted()}` : "Not submitted yet."}</p>
</form>
);
}With name, Select renders one input type="hidden" for each selected value, so the form submits the value under that name. The submitted value is the option key, which is optionValue converted to a string. For string options, that is the string. With multiple, each selected value submits under the same name. With nothing selected, or when the select is disabled, the form submits nothing for that name. Hidden inputs take no part in native validation, so check required before you submit.
Styled parts API
Import the ready Select and createSelectOptions from @codeui/solid/select. To change the structure, import the parts from @codeui/solid/select/parts.
import * as S from "@codeui/solid/select/parts";
<S.Root
options={["PNG", "JPEG"]}
itemComponent={props => (
<S.Item item={props.item}>
<S.ItemLabel>{props.item.rawValue}</S.ItemLabel>
</S.Item>
)}
>
<S.Label>Format</S.Label>
<S.Trigger>
<S.Value<string>>{state => state.selectedOption()}</S.Value>
</S.Trigger>
<S.Portal>
<S.Content>
<S.Listbox />
</S.Content>
</S.Portal>
</S.Root>The anatomy table lists the styled elements. Set size and variant on Trigger. Set the same size on Root to size the label and messages. Use Portal to mount the list and Section to render option groups. To submit selected keys with a form, put FormValue inside Root with the field name and the same disabled state.
Accessibility
Keyboard
| Key | Action |
|---|---|
| Tab or Shift+Tab | Moves focus to or away from the trigger. |
| Enter, Space, or ArrowDown | Opens the list and highlights the selected option, or the first one. |
| ArrowUp | Opens the list and highlights the selected option, or the last one. |
| A printable character | Moves to the next option whose text starts with the typed characters. |
| ArrowDown or ArrowUp in the list | Moves the highlight. Disabled options are skipped. |
| Home or End in the list | Moves the highlight to the first or last option. |
| Enter or Space in the list | Selects the highlighted option. In single mode, the list closes. |
| Escape | Closes the list and keeps the value. |
ARIA
The trigger is a button with aria-haspopup="listbox" and aria-expanded. Its name comes from the visible label. Pass aria-label only when there is no visible label. The list is a listbox, and each item is an option with aria-selected. Disabled options have aria-disabled="true". description and errorMessage are linked to the trigger with aria-describedby.
Focus
When the list opens, focus moves into it, onto the selected option or the first one. When it closes, by selection or by Escape, focus returns to the trigger. The trigger draws its focus ring from --cui-focus-color.
SSR notes
The label, the trigger with the selected value, and the messages render on the server. The list renders in a portal only on the client, after the user opens it. Kobalte generates the ids that link the label and the messages, and they match between the server and the client. Keep options and value equal on both sides to avoid a hydration mismatch in the trigger text.
Theming hooks
The trigger uses the shared field styles. The list uses the menu surfaces.
--cui-surface-input,--cui-text-input,--cui-border-input, and--cui-text-hintfor the trigger and its placeholder.--cui-text-dangerfor the invalid border and the error message.--cui-surface-dialogfor the disabled fill.--cui-focus-colorfor the focus ring.--cui-border-widthand--cui-border-width-strong, the second for theinlinevariant.--cui-control-height-{xs,sm,md,lg},--cui-font-size-{xs,sm,md,lg}, and--cui-radius-{xs,sm,md,lg,xl}for sizes.--cui-surface-menu,--cui-border-menu,--cui-shadow-menu, and--cui-text-menufor the list.--cui-surface-menu-hoverfor the highlighted option.--cui-space-{1,2,3},--cui-font-weight-normal, and--cui-control-height-mdfor list items.--cui-motion-duration-{fast,normal}and--cui-motion-ease-outfor the list's Pop: in fromscale(0.96)over 160ms and out toscale(0.98)over 120ms, from the trigger side. Opened from the keyboard, the list appears in place (data-motion="none").
Each brace expands to a separate variable. See Inkstone color and motion.
Composition examples
- Submit with a form on this page reads the value from
FormDatathroughname. - Object options with
createSelectOptionsstores an id while the list shows names.
Related
- Combobox adds a text input that filters the options.
- Listbox shows the options inline, with no popover.
- CommandMenu runs actions instead of holding a value.
- Options and collections documents
createSelectOptions.