Skip to main content

BaseSelect

Compose a custom listbox with selection, navigation, and popup ownership.

Props
Slots

Anatomy#

BaseSelect [component; no DOM]
├── BaseSelect.Control [part; slot=control]
│   └── BaseSelect.Trigger [part; slot=trigger]
└── positioner [internal]
    └── BaseSelect.Content [part; slot=content]
        ├── BaseSelect.Listbox [part; slot=listbox]
        │   ├── BaseSelect.Group [part; slot=group]
        │   │   ├── BaseSelect.GroupLabel [part; slot=groupLabel]
        │   │   └── BaseSelect.Item [part; slot=item]
        │   ├── BaseSelect.Item [part; slot=item]
        │   └── BaseSelect.Separator [part; slot=separator]
        └── BaseSelect.Empty [part; slot=empty]

Control is an optional layout container and floating anchor; without it, Content anchors to the registered focus owner.

Usage#

Use BaseSelect to build a custom selection control from a trigger and listbox parts. It manages selected values, open state, keyboard navigation, and native form values. Your application owns filtering, query text, grouping, and item creation.

For a ready-made field, start with Select, Combobox, or MultiSelect.

import { BaseSelect } from 'moraine'

export function Example() {
  return (
    <BaseSelect items={[{ label: 'Option A', value: 'a' }]}>
      <BaseSelect.Control>
        <BaseSelect.Trigger>Choose an option</BaseSelect.Trigger>
      </BaseSelect.Control>
      <BaseSelect.Content>
        <BaseSelect.Listbox>
          <BaseSelect.Item item={{ label: 'Option A', value: 'a' }}>Option A</BaseSelect.Item>
        </BaseSelect.Listbox>
      </BaseSelect.Content>
    </BaseSelect>
  )
}

Values and form submission#

value, defaultValue, and onValueChange always use arrays, even for single selection; without multiple, only the first entry is used. value={undefined} keeps the selection uncontrolled and value={[]} keeps it controlled and empty. Choosing an item closes the popup unless you set multiple or closeOnSelect={false}. Set name to submit the selection with the enclosing native form; use serializeValue to change or omit a submitted value.

Control and focus ownership#

Control is an optional, non-interactive layout container and floating anchor. It does not toggle, own keyboard navigation, become a tab stop, or receive role="combobox". Trigger is the primary select-like focus owner and activator. If Control is omitted, Content anchors to the registered focus owner.

For an editable composition, bind your own <input> with createBaseSelectSearchInput from moraine/utils. Call it in a component rendered inside BaseSelect, passing BaseSelect.useContext() as state, and spread inputProps on the input. The helper registers the input as the focus owner and adds the combobox ARIA attributes and keyboard handling. It does not make the input the floating anchor, so render a BaseSelect.Control around it. You own the input, the canonical source, filtering, and query reset. No BaseSelect.Trigger is required in that pattern.

import { BaseSelect } from 'moraine'
import { createBaseSelectSearchInput } from 'moraine/utils'

function SearchControl(props: { query: () => string; setQuery: (value: string) => string }) {
  const input = createBaseSelectSearchInput({
    state: BaseSelect.useContext(),
    searchValue: props.query,
    setSearchValue: props.setQuery,
  })
  return (
    <BaseSelect.Control>
      <input {...input.inputProps} />
    </BaseSelect.Control>
  )
}

Item fields#

BaseSelect.Item takes the collection entry through the item prop: <BaseSelect.Item item={item} />. Other props are DOM and rendering props for the rendered <div>. Custom item fields are available through render state, and arbitrary item fields never leak into DOM attributes: <BaseSelect.Item<MyItem> item={item}>{(state) => state.item.custom}</BaseSelect.Item>. Without children, Item renders item.label.

Filtered collections#

items is the flat list of every item you render as BaseSelect.Item; an item whose value is not in items cannot be selected. By default, items is both the canonical data source and the active navigation collection. Values must be unique. Groups and separators are rendering concerns and do not belong in items.

For custom filtered compositions such as searchable controls, provide getItemByValue alongside a filtered items view:

<BaseSelect items={filteredItems()} getItemByValue={(value) => allItemsByValue.get(value)}>
  {/* ... */}
</BaseSelect>

The filtered items array controls which options users can navigate. getItemByValue looks up selected items in the full collection, so labels, disabled state, and form values remain available when an item is filtered out.

Styling#

BaseSelect exposes the style slots control, trigger, content, listbox, item, group, groupLabel, separator, and empty through classes and styles on the root. Each part also accepts class and style for its own element. See Customization and Theming for nested Provider, Portal, and class-merging behavior.

Examples#

Pick a grouped framework#

Compose groups, group labels, and item render state when Select’s built-in collection is not enough. Resolve the trigger label from the full collection.

import { BaseSelect, Button, Icon } from 'moraine'
import { For } from 'solid-js'

const GROUPS = [
  {
    label: 'Frontend',
    items: [
      { value: 'solid', label: 'Solid', description: 'Fine-grained reactive UI' },
      { value: 'react', label: 'React', description: 'Component-based UI' },
    ],
  },
  {
    label: 'Meta-frameworks',
    items: [
      { value: 'astro', label: 'Astro', description: 'Content-focused web framework' },
      { value: 'sveltekit', label: 'SvelteKit', description: 'Application framework for Svelte' },
    ],
  },
]

const FRAMEWORKS = GROUPS.flatMap((group) => group.items)

export default function Example() {
  return (
    <BaseSelect items={FRAMEWORKS} getItemLabel={(item) => `${item.value} ${item.description}`}>
      <BaseSelect.Control>
        <BaseSelect.Trigger
          as={Button}
          variant="outline"
          class="min-w-52 justify-between"
          trailing="i-lucide:chevrons-up-down"
        >
          {(state) => (
            <span>
              {FRAMEWORKS.find((item) => item.value === state.value[0])?.label ??
                'Select framework…'}
            </span>
          )}
        </BaseSelect.Trigger>
      </BaseSelect.Control>
      <BaseSelect.Content>
        <BaseSelect.Listbox>
          <For each={GROUPS}>
            {(group) => (
              <BaseSelect.Group>
                <BaseSelect.GroupLabel>{group.label}</BaseSelect.GroupLabel>
                <For each={group.items}>
                  {(item) => (
                    <BaseSelect.Item item={item}>
                      {(state) => (
                        <>
                          <Icon
                            name="i-lucide:check"
                            class={state.selected ? 'opacity-100' : 'opacity-0'}
                          />
                          <span>
                            {state.item.label}
                            <small class="text-muted-foreground block">
                              {state.item.description}
                            </small>
                          </span>
                        </>
                      )}
                    </BaseSelect.Item>
                  )}
                </For>
              </BaseSelect.Group>
            )}
          </For>
        </BaseSelect.Listbox>
        <BaseSelect.Empty>No frameworks found.</BaseSelect.Empty>
      </BaseSelect.Content>
    </BaseSelect>
  )
}

Search a custom listbox#

Own the query and the filtered items, and bind the input with createBaseSelectSearchInput. Pass getItemByValue so a selected option still resolves after it leaves the filtered view.

import { BaseSelect, Icon } from 'moraine'
import { createBaseSelectSearchInput } from 'moraine/utils'
import type { BaseSelectSearchInputOptions } from 'moraine/utils'
import { createMemo, createSignal, For } from 'solid-js'

const FRAMEWORKS = [
  { value: 'solid', label: 'Solid', description: 'Fine-grained reactive UI' },
  { value: 'react', label: 'React', description: 'Component-based UI' },
  { value: 'astro', label: 'Astro', description: 'Content-focused web framework' },
  { value: 'sveltekit', label: 'SvelteKit', description: 'Application framework for Svelte' },
]

function SearchControl(
  props: Pick<BaseSelectSearchInputOptions, 'searchValue' | 'setSearchValue'>,
) {
  const state = BaseSelect.useContext()
  const input = createBaseSelectSearchInput({
    state,
    searchValue: () => props.searchValue(),
    setSearchValue: (value) => props.setSearchValue(value),
  })
  return (
    <BaseSelect.Control class="px-2 border border-input rounded-md flex w-64 items-center">
      <input
        {...input.inputProps}
        class="py-1.5 outline-none bg-transparent flex-1"
        placeholder="Search frameworks…"
      />
      <button
        type="button"
        tabIndex={-1}
        aria-label="Toggle frameworks"
        onPointerDown={(event) => {
          event.preventDefault()
          event.stopPropagation()
          state.focusOwner()?.focus()
        }}
        onClick={(event) => {
          event.stopPropagation()
          state.setOpen(!state.open())
        }}
      >
        <Icon name="i-lucide:chevrons-up-down" />
      </button>
    </BaseSelect.Control>
  )
}

export default function Example() {
  const [searchValue, setSearchValue] = createSignal('')
  const items = createMemo(() => {
    const query = searchValue().toLowerCase()
    return query
      ? FRAMEWORKS.filter(
          (item) =>
            item.label.toLowerCase().includes(query) ||
            item.description.toLowerCase().includes(query),
        )
      : FRAMEWORKS
  })
  return (
    <BaseSelect
      items={items()}
      getItemByValue={(value) => FRAMEWORKS.find((item) => item.value === value)}
      getItemLabel={(item) => `${item.label} ${item.description}`}
      onExitComplete={() => setSearchValue('')}
    >
      <SearchControl searchValue={searchValue} setSearchValue={setSearchValue} />
      <BaseSelect.Content>
        <BaseSelect.Listbox>
          <For each={items()}>
            {(item) => (
              <BaseSelect.Item item={item}>
                {(state) => (
                  <>
                    <Icon
                      name="i-lucide:check"
                      class={state.selected ? 'opacity-100' : 'opacity-0'}
                    />
                    <span>
                      {state.item.label}
                      <small class="text-muted-foreground block">{state.item.description}</small>
                    </span>
                  </>
                )}
              </BaseSelect.Item>
            )}
          </For>
        </BaseSelect.Listbox>
        <BaseSelect.Empty>No frameworks found.</BaseSelect.Empty>
      </BaseSelect.Content>
    </BaseSelect>
  )
}

Select multiple frameworks#

Set multiple and read state.value as an array. Summarize the whole selection in the trigger instead of showing a single label. The popup stays open after each choice.

import { BaseSelect, Button, Icon } from 'moraine'
import type { BaseSelectT } from 'moraine'
import { For } from 'solid-js'

const FRAMEWORKS = [
  { value: 'solid', label: 'Solid' },
  { value: 'react', label: 'React' },
  { value: 'vue', label: 'Vue' },
] satisfies BaseSelectT.Item[]

export default function Example() {
  return (
    <BaseSelect items={FRAMEWORKS} multiple defaultValue={['solid']} name="frameworks">
      <BaseSelect.Control>
        <BaseSelect.Trigger as={Button} variant="outline" class="min-w-52">
          {(state) => <span>{state.value.length} framework(s) selected</span>}
        </BaseSelect.Trigger>
      </BaseSelect.Control>
      <BaseSelect.Content>
        <BaseSelect.Listbox>
          <For each={FRAMEWORKS}>
            {(item) => (
              <BaseSelect.Item item={item}>
                {(state) => (
                  <>
                    <Icon
                      name="i-lucide:check"
                      class={state.selected ? 'opacity-100' : 'opacity-0'}
                    />
                    {state.item.label}
                  </>
                )}
              </BaseSelect.Item>
            )}
          </For>
        </BaseSelect.Listbox>
        <BaseSelect.Empty>No frameworks found.</BaseSelect.Empty>
      </BaseSelect.Content>
    </BaseSelect>
  )
}

Submit a native form value#

Give the root a name. BaseSelect writes the selected value into the enclosing native form without createForm.

import { BaseSelect, Button } from 'moraine'
import type { BaseSelectT } from 'moraine'
import { createSignal, For } from 'solid-js'

const FRAMEWORKS = [
  { value: 'solid', label: 'Solid' },
  { value: 'react', label: 'React' },
  { value: 'vue', label: 'Vue' },
] satisfies BaseSelectT.Item[]

export default function Example() {
  const [submitted, setSubmitted] = createSignal('Not submitted')
  return (
    <form
      class="flex gap-2 items-start"
      onSubmit={(event) => {
        event.preventDefault()
        const value = new FormData(event.currentTarget).get('framework')
        setSubmitted(typeof value === 'string' ? value : 'No selection')
      }}
    >
      <BaseSelect items={FRAMEWORKS} name="framework" required>
        <BaseSelect.Control>
          <BaseSelect.Trigger as={Button} variant="outline" class="min-w-52">
            {(state) => (
              <span>
                {FRAMEWORKS.find((item) => item.value === state.value[0])?.label ??
                  'Select framework…'}
              </span>
            )}
          </BaseSelect.Trigger>
        </BaseSelect.Control>
        <BaseSelect.Content>
          <BaseSelect.Listbox>
            <For each={FRAMEWORKS}>
              {(item) => <BaseSelect.Item item={item}>{item.label}</BaseSelect.Item>}
            </For>
          </BaseSelect.Listbox>
        </BaseSelect.Content>
      </BaseSelect>
      <Button type="submit">Submit</Button>
      <output class="text-sm text-muted-foreground self-center">{submitted()}</output>
    </form>
  )
}

API Reference#

Attributes#

Attributes
data-closed
Slot: base-select-controlbase-select-triggerbase-select-content
Description: Present when disclosure or transition content is closed.
data-disabled
Slot: base-select-controlbase-select-triggerbase-select-item
Description: Present when the component, slot, or item is disabled.
data-expanded
Slot: base-select-controlbase-select-triggerbase-select-content
Description: Present when the panel, accordion, or menu is expanded.
data-invalid
Slot: base-select-controlbase-select-trigger
Description: Present when the field or form has a validation error.
data-readonly
Slot: base-select-control
Description: Present when the field is in read-only mode.
data-required
Slot: base-select-control
Description: Present when the field input is required.
data-side
Slot: base-select-content
Description: Stores the resolved floating or drawer content side.
data-highlighted
Slot: base-select-item
Description: Present when the item is highlighted by pointer or keyboard navigation.
data-selected
Slot: base-select-item
Description: Present when the item or tab is selected.

Props#

BaseSelect#

Prop

Control#

Renders a <div> element by default.

Prop

Trigger#

Renders a <button> element by default.

Prop

Content#

Renders a <div> element by default.

Prop

Listbox#

Renders a <div> element by default.

Prop

Item#

Renders a <div> element by default.

Prop

Group#

Renders a <div> element by default.

Prop

GroupLabel#

Renders a <div> element by default.

Prop

Separator#

Renders a <div> element by default.

Prop

Empty#

Renders a <div> element by default.

Prop