Skip to Content
CodeUI

Options and collections

@codeui/solid v0.3.0

Helpers that turn your data into options for Select, Combobox, and CommandMenu.

Each list component reads its options in its own way. Pick the helper that matches the component.

ComponentWhat it holdsHelper
SelectOne or more values picked from a popover list.createSelectOptions
ComboboxOne value picked by typing into a filtered list.createComboboxOptions
ListboxOne or more values in a list that stays on the page.None. It takes options with Kobalte's option keys.
CommandMenuNo value. It runs the action the user picks.filterCommandItems

The two option helpers solve the same problem. You keep a plain value in your state, such as a theme id, while the component works with option objects. Both return options, optionToValue, optionFromValue, props, and controlled. Their configuration and their props() differ, as the sections below show.

createSelectOptions

import { createSelectOptions } from "@codeui/solid";

function createSelectOptions<T, C extends { key?: string; valueKey?: string }>(
	values: readonly T[] | Accessor<readonly T[]>,
	config?: C,
): CreateSelectOptionsReturn<T, C>;
Theme

Stored value: dracula

options-and-collections/select-options.tsx
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" },
];

export default function SelectOptionsHelperDemo() {
	const [themeId, setThemeId] = createSignal("dracula");
	const themeOptions = createSelectOptions(themes, { key: "name", valueKey: "id" });
	return (
		<>
			<Select
				aria-label="Theme"
				label="Theme"
				options={themeOptions.options()}
				{...themeOptions.props()}
				value={themeOptions.optionFromValue(themeId())}
				onChange={option => {
					const id = themeOptions.optionToValue(option);
					if (id) setThemeId(id);
				}}
			/>
			<p>Stored value: {themeId()}</p>
		</>
	);
}

Parameters

ParameterDescription
valuesThe source items, as an array or an accessor that returns one.
config.keyThe field to show as the label. Without it, the label is the whole item.
config.valueKeyThe field to use as the value. Without it, the value is the whole item.

Return value

MemberDescription
options()The items mapped to { label, value }. Pass it to options.
props()optionValue, optionTextValue, itemLabel, and valueComponent for Select. It does not include options.
optionFromValue(value)The option whose value equals value with ===, or undefined.
optionToValue(option)The value of the option, or undefined for null or undefined.
controlled(value, onChange){ value, onChange } to spread on Select. value is an accessor of your plain value. onChange receives the plain value and the option.

The value type follows valueKey. With { valueKey: "id" } on Theme[], the value is Theme["id"].

Edge cases

  • controlled treats every falsy value as no selection. A value of 0 or "" never selects an option. Use optionFromValue directly for those values.
  • There is no disabled mapping. Pass optionDisabled to Select as a function over the { label, value } option.
  • optionTextValue uses the label when it is a string, and String(value) otherwise. Type-ahead reads it.
  • options() builds new option objects on each call. Compare options by value, not by identity.
  • With an accessor source, the options follow the accessor. Write a new array to the signal to update the list.

createComboboxOptions

import { createComboboxOptions } from "@codeui/solid";
// also exported from "@codeui/solid/combobox/parts"

function createComboboxOptions<T extends string | number>(
	values: readonly T[] | Accessor<readonly T[]>,
): CreateComboboxOptionsReturn<T, T>;

function createComboboxOptions<T extends object, C extends ComboboxOptionsConfig<T>>(
	values: readonly T[] | Accessor<readonly T[]>,
	config: C,
): CreateComboboxOptionsReturn<T[C["valueKey"]], T>;

Fira Code, ligatures on

options-and-collections/combobox-options.tsx
import { createSignal } from "solid-js";
import { Combobox, createComboboxOptions } from "@codeui/solid";

type Font = { id: string; name: string; ligatures: boolean; premium: boolean };

const fonts: Font[] = [
	{ id: "jetbrains-mono", name: "JetBrains Mono", ligatures: true, premium: false },
	{ id: "fira-code", name: "Fira Code", ligatures: true, premium: false },
	{ id: "source-code-pro", name: "Source Code Pro", ligatures: false, premium: false },
	{ id: "operator-mono", name: "Operator Mono", ligatures: false, premium: true },
];

export default function ComboboxOptionsHelperDemo() {
	const [fontId, setFontId] = createSignal<string | undefined>("fira-code");
	const fontOptions = createComboboxOptions(fonts, {
		valueKey: "id",
		labelKey: "name",
		disabledKey: "premium",
	});
	const font = () => fontOptions.optionFromValue(fontId())?.item;
	return (
		<>
			<Combobox
				{...fontOptions.props()}
				{...fontOptions.controlled(fontId, setFontId)}
				label="Font"
				placeholder="Search fonts"
			/>
			<p>
				{font() ? `${font()!.name}, ligatures ${font()!.ligatures ? "on" : "off"}` : "No font"}
			</p>
		</>
	);
}

Parameters

ParameterDescription
valuesThe source items, as an array or an accessor that returns one. Strings and numbers need no config.
config.valueKeyRequired for objects. A field whose type is string or number.
config.labelKeyRequired for objects. A string field. The input shows it and the filter searches it.
config.disabledKeyOptional. A boolean field. true disables the option.

TypeScript checks each key against the field types, so a labelKey that points to a number field does not compile.

Return value

ComboboxOption<Value, Item> is { value, label, disabled, item }. item is your original object.

MemberDescription
options()The normalized options.
props()options, plus optionValue: "value", optionTextValue: "label", optionLabel: "label", and optionDisabled: "disabled". Spread it on Combobox or on Root from @codeui/solid/combobox/parts.
optionFromValue(value)The option whose value equals value with ===. It returns undefined for null, undefined, or no match.
optionToValue(option)The value of the option, or undefined.
controlled(value, onChange){ value, onChange } to spread on Combobox. value is the matching option or null. onChange receives the plain value and the option.

ComboboxOption, ComboboxOptionsConfig, and CreateComboboxOptionsReturn are exported from @codeui/solid and @codeui/solid/combobox/parts.

Edge cases

  • controlled always passes a value, null when nothing matches. The combobox is then controlled. Clearing the text calls your onChange with undefined, and the selection clears. See Clear a controlled value.
  • options() caches the normalized list until the source array changes identity. Mutating the array in place does not update the options. Write a new array.
  • A form submits the value as a string. A numeric id of 3 arrives as "3".
  • label must be a string, because the input shows it and the filter searches it. Use renderOption on Combobox for rich content in the list.

Reactive options

options-and-collections/reactive.tsx
import { createSignal } from "solid-js";
import { Button, Combobox, createComboboxOptions } from "@codeui/solid";

type Preset = { id: number; name: string };

export default function ReactiveOptionsDemo() {
	const [presets, setPresets] = createSignal<Preset[]>([
		{ id: 1, name: "Blog header" },
		{ id: 2, name: "Tweet card" },
	]);
	const [presetId, setPresetId] = createSignal<number | undefined>(1);
	const presetOptions = createComboboxOptions(presets, { valueKey: "id", labelKey: "name" });
	const addPreset = () => {
		const id = presets().length + 1;
		setPresets([...presets(), { id, name: `Preset ${id}` }]);
	};
	return (
		<>
			<Combobox
				{...presetOptions.props()}
				{...presetOptions.controlled(presetId, setPresetId)}
				label="Preset"
				placeholder="Search presets"
			/>
			<Button variant="secondary" onClick={addPreset}>
				Save current as preset
			</Button>
		</>
	);
}

Pass a signal accessor as values. Each new array rebuilds the options, and the open list updates. The controlled value stays selected as long as an option with that value still exists.

filterCommandItems

import { filterCommandItems, type CommandItem } from "@codeui/solid";

function filterCommandItems<T extends CommandItem>(items: readonly T[], query: string): readonly T[];
  • Export: Export as PNG
  • Export: Export as SVG
  • Share: Copy share link
  • Theme: Dracula
options-and-collections/filter-command-items.tsx
import { createSignal, For } from "solid-js";
import { filterCommandItems, TextField, type CommandItem } from "@codeui/solid";

const commands: CommandItem[] = [
	{ id: "export-png", textValue: "Export as PNG", label: "Export as PNG", group: "Export" },
	{ id: "export-svg", textValue: "Export as SVG", label: "Export as SVG", group: "Export" },
	{ id: "copy-link", textValue: "Copy share link", label: "Copy share link", group: "Share" },
	{
		id: "theme-dracula",
		textValue: "Dracula",
		label: "Dracula",
		description: "Dark theme",
		group: "Theme",
	},
];

export default function FilterCommandItemsDemo() {
	const [query, setQuery] = createSignal("");
	const results = () => filterCommandItems(commands, query());
	return (
		<>
			<TextField label="Search commands" placeholder="Try export png or dark" value={query()} onChange={setQuery} />
			<ul>
				<For each={results()} fallback={<li>No command matches.</li>}>
					{command => (
						<li>
							{command.group}: {command.label}
						</li>
					)}
				</For>
			</ul>
		</>
	);
}

Parameters

ParameterDescription
itemsThe command items. Each needs a unique id and a plain-text textValue.
queryThe search text.

Return value

The items that match every word of the query, in their original order. An item matches a word when its textValue, group, section, or plain-string description contains the word. Matching ignores case.

Edge cases

  • An empty query, or one with only spaces, returns the items array itself.
  • Matching is by substring, not fuzzy. "exp png" matches "Export as PNG". "epng" does not.
  • A description that is JSX is not searched. Put the searchable words in textValue or pass a string description.
  • CommandMenu uses this function when you leave out its filter prop. To change the matching, pass a filter with the same signature. Call filterCommandItems inside it to extend the default.
  • Select consumes createSelectOptions.
  • Combobox consumes createComboboxOptions.
  • CommandMenu uses filterCommandItems as its default filter.

On this page