Skip to main content

Select

Choose one item from a non-editable collection.

Props
Slots

Anatomy#

Select [component; no DOM]
├── control [slot]
│   ├── trigger [slot]
│   │   ├── leading [slot]
│   │   ├── value [slot]
│   │   └── trailing [slot]
│   └── clear [slot]
└── positioner [internal]
    └── content [slot]
        └── listbox [slot]
            ├── group [slot]
            │   └── groupLabel [slot]
            ├── separator [slot]
            └── item [slot]
                ├── itemLeading [slot]
                ├── itemWrapper [slot]
                │   ├── itemLabel [slot]
                │   └── itemDescription [slot]
                └── itemIndicator [slot]

Select renders the portaled popup internally; the popup names are style slots, not attached parts. Use BaseSelect to compose the listbox yourself.

Usage#

Use Select for one choice from a non-editable collection. Use Combobox when users need to type a query or the collection is large enough to need virtualization, MultiSelect for several collection values, or BaseSelect to compose the listbox yourself.

import { Field, Select } from 'moraine'

export function Example() {
  return (
    <Field label="Size">
      <Select
        items={[
          { label: 'Small', value: 'sm' },
          { label: 'Large', value: 'lg' },
        ]}
        placeholder="Choose a size"
      />
    </Field>
  )
}

String items#

Pass strings when the label and value are identical. You can mix strings and objects at the root or inside a group. Whitespace is preserved, and an empty string is a valid value.

<Select items={['Apple', 'Banana']} defaultValue="Apple" />
<Select
  items={[
    'Apple',
    { value: 'pear', label: 'Pear', description: 'Fresh fruit' },
    { type: 'group', label: 'More fruit', items: ['Banana'] },
  ]}
/>

A string item normalizes to { value, label } with both set to the string, so 'Apple' becomes { value: 'Apple', label: 'Apple' }. Object items keep their custom fields, and SelectT.NormalizedItem<TItem> is the item type passed to callbacks. Item values must be unique across the collection. When two items share a value, the first one wins (including a string that collides with an object), and development builds log an error.

Value and collection#

The value slot shows the selected label, or String(value) when the value matches no item.

Pair value with onValueChange for controlled selection, or use defaultValue for an initial uncontrolled choice. value={undefined} keeps the selection uncontrolled; value={null} keeps it controlled and empty. onValueChange receives null when the selection is cleared, and inside a form field, clearing writes null.

<Select items={countries} value={selected()} onValueChange={setSelected} clearable />

Clear and loading#

clearable shows a clear button beside the trigger while a value is selected. Clicking it clears the selection without toggling the popup. Backspace or Delete on the focused trigger also clears. Clearing calls onValueChange(null), then onClear, and returns focus to the trigger. Neither fires while the select is disabled or read-only.

loading swaps the trailing icon for loadingIcon and hides the clear button. It does not disable the select.

The popup opens below the control and aligns to its start edge. placement, align, gutter, shift, flip, slide, and overflowPadding adjust that position. closeOnEscape and closeOnOutsideClick default to true; set either to false to block that dismissal and listen for it with onClosePrevented. Combobox and MultiSelect accept the same props. open, defaultOpen, and onOpenChange control the popup state.

<Select items={items} placement="top" align="end" flip={false} />

Keyboard interaction#

Key Behavior
Enter / Space Open the popup, or commit the highlighted option while open
ArrowDown / ArrowUp Open the popup and move the highlight through enabled options
Home / End Highlight the first or last enabled option while open
PageUp / PageDown Move the highlight by one page of options while open
Printable key Typeahead: highlight the matching label while open, select it if closed
Backspace / Delete Clear the value when clearable and a value is selected
Escape Close the popup without changing the value
Tab Close the popup and move focus on

Examples#

Choose a subscription plan#

Put an icon and description on each item when the choice needs more than a label. No custom item template is required.

import { Select } from 'moraine'
import type { SelectT } from 'moraine'

const PLANS: SelectT.Item[] = [
  {
    label: 'Starter',
    value: 'starter',
    icon: 'i-lucide:sparkles',
    description: 'Up to 3 members · Free forever',
  },
  {
    label: 'Professional',
    value: 'pro',
    icon: 'i-lucide:zap',
    description: '$19/mo · Ideal for growing teams',
  },
  {
    label: 'Team',
    value: 'team',
    icon: 'i-lucide:rocket',
    description: '$49/mo · Advanced collaboration tools',
  },
  {
    label: 'Enterprise',
    value: 'enterprise',
    icon: 'i-lucide:shield-check',
    description: 'Custom pricing · Dedicated support & SLA',
  },
]

export function RichItems() {
  return (
    <div class="max-w-sm w-full space-y-2">
      <label class="text-xs text-muted-foreground font-medium block">Subscription Plan</label>
      <Select items={PLANS} defaultValue="pro" placeholder="Choose your plan..." />
    </div>
  )
}

Assign a member role#

Pick one permission role from a short collection. Keep the selected value as the role id.

import { Select } from 'moraine'
import type { SelectT } from 'moraine'

const ROLES: SelectT.Item[] = [
  {
    label: 'Owner',
    value: 'owner',
    icon: 'i-lucide:crown',
    description: 'Full access to all resources and billing',
  },
  {
    label: 'Admin',
    value: 'admin',
    icon: 'i-lucide:shield',
    description: 'Can manage team members and settings',
  },
  {
    label: 'Member',
    value: 'member',
    icon: 'i-lucide:user',
    description: 'Can create and edit team projects',
  },
  {
    label: 'Viewer',
    value: 'viewer',
    icon: 'i-lucide:eye',
    description: 'Read-only access to published workflows',
  },
]

export function UserAssignee() {
  return (
    <div class="max-w-sm w-full space-y-2">
      <label class="text-xs text-muted-foreground font-medium block">Member Permission Role</label>
      <Select items={ROLES} defaultValue="member" placeholder="Assign a role..." />
    </div>
  )
}

Choose a workspace timezone#

Organize options with type: 'group'. Insert { type: 'separator' } between groups or items. Group labels and separators are excluded from selection and keyboard navigation.

import { Select } from 'moraine'
import type { SelectT } from 'moraine'

const TIMEZONE_GROUPS: SelectT.Entry[] = [
  {
    label: 'Americas',
    type: 'group',
    items: [
      { label: 'America/New_York (UTC-5)', value: 'America/New_York' },
      { label: 'America/Chicago (UTC-6)', value: 'America/Chicago' },
      { label: 'America/Los_Angeles (UTC-8)', value: 'America/Los_Angeles' },
      { label: 'America/Sao_Paulo (UTC-3)', value: 'America/Sao_Paulo' },
    ],
  },
  {
    label: 'Europe',
    type: 'group',
    items: [
      { label: 'Europe/London (UTC+0)', value: 'Europe/London' },
      { label: 'Europe/Frankfurt (UTC+1)', value: 'Europe/Frankfurt' },
      { label: 'Europe/Paris (UTC+1)', value: 'Europe/Paris' },
    ],
  },
  {
    label: 'Asia Pacific',
    type: 'group',
    items: [
      { label: 'Asia/Tokyo (UTC+9)', value: 'Asia/Tokyo' },
      { label: 'Asia/Singapore (UTC+8)', value: 'Asia/Singapore' },
      { label: 'Australia/Sydney (UTC+11)', value: 'Australia/Sydney' },
    ],
  },
]

export function GroupedItems() {
  return (
    <div class="max-w-xs w-full space-y-2">
      <label class="text-xs text-muted-foreground font-medium block">Workspace Timezone</label>
      <Select
        items={TIMEZONE_GROUPS}
        defaultValue="Europe/London"
        placeholder="Select timezone..."
      />
    </div>
  )
}

Load more options on scroll#

Use onBottomReached and scrollThreshold to append pages as the listbox approaches the bottom. Drive loading from the in-flight request.

import { Select } from 'moraine'
import type { SelectT } from 'moraine'
import { createSignal } from 'solid-js'

export function InfiniteScroll() {
  function makeOptions(count: number, offset = 0): SelectT.Item[] {
    return Array.from({ length: count }, (_, i) => ({
      label: `Option ${offset + i + 1}`,
      value: `opt-${offset + i + 1}`,
    }))
  }

  const [infiniteOptions, setInfiniteOptions] = createSignal<SelectT.Item[]>(makeOptions(20))

  const [loadingMore, setLoadingMore] = createSignal(false)

  return (
    <div class="w-80 space-y-2">
      <Select
        items={infiniteOptions()}
        classes={{
          listbox: 'max-h-100',
        }}
        onBottomReached={() => {
          if (loadingMore()) {
            return
          }
          setLoadingMore(true)
          setTimeout(() => {
            const next = infiniteOptions().length
            setInfiniteOptions((prev) => [...prev, ...makeOptions(10, next)])
            setLoadingMore(false)
          }, 1000)
        }}
        scrollThreshold={30}
        loading={loadingMore()}
        placeholder="Scroll to load more..."
      />
      <p class="text-xs text-muted-foreground">Total items: {infiniteOptions().length}</p>
    </div>
  )
}

Bind an empty select to a form#

For an empty form.Field-bound Select, initialize the field with null and accept null in the schema. required is satisfied by any selected value, including one whose item is disabled. In that case the select passes constraint validation but submits no value, as a native <select> does with a disabled selected option.

import { Button, createForm, Select } from 'moraine'
import type { SelectT } from 'moraine'
import { createSignal } from 'solid-js'
import * as v from 'valibot'

const COUNTRIES = [
  { label: 'United States', value: 'us' },
  { label: 'Germany', value: 'de' },
  { label: 'Japan', value: 'jp' },
  { label: 'United Kingdom', value: 'uk' },
  { label: 'Canada', value: 'ca' },
] satisfies SelectT.Item[]

export function FormIntegration() {
  const [submittedCountry, setSubmittedCountry] = createSignal<string | null>(null)
  const form = createForm({
    schema: v.object({
      country: v.pipe(
        v.nullable(v.string()),
        v.check(
          (value): value is string => value !== null,
          'Please select your country of residence.',
        ),
      ),
    }),
    initialInput: { country: null },
    validate: 'input',
  })

  return (
    <form.Form onSubmit={(output) => setSubmittedCountry(output.country)}>
      <div class="max-w-xl space-y-4">
        <form.Field
          name="country"
          label="Country / Region"
          description="Used for tax calculation and regional billing."
          required
        >
          <Select items={COUNTRIES} placeholder="Select a country..." />
        </form.Field>
        <div class="flex gap-3 items-center">
          <Button type="submit" variant="soft" tone="neutral" size="sm">
            Validate
          </Button>
          <p class="text-xs text-muted-foreground">
            Selected country: {submittedCountry() || 'none'}
          </p>
        </div>
      </div>
    </form.Form>
  )
}

Own the selected country code#

Pair value with onValueChange. Clearing writes null. Nearby copy can read the same signal.

import { Button, Select } from 'moraine'
import type { SelectT } from 'moraine'
import { createSignal } from 'solid-js'

const COUNTRIES: SelectT.Item[] = [
  { label: 'United States', value: 'us' },
  { label: 'Germany', value: 'de' },
  { label: 'Japan', value: 'jp' },
  { label: 'United Kingdom', value: 'uk' },
  { label: 'Canada', value: 'ca' },
]

export function UsageValue() {
  const [selected, setSelected] = createSignal<string | undefined>('de')

  return (
    <div class="max-w-xs w-full space-y-3">
      <Select
        placeholder="Select a country..."
        leading="i-lucide:globe"
        items={COUNTRIES}
        value={selected()}
        onValueChange={setSelected}
        clearable
      />
      <div class="text-xs flex items-center justify-between">
        <span class="text-muted-foreground">
          Selected code:{' '}
          <span class="text-foreground font-medium font-mono">{selected() ?? 'undefined'}</span>
        </span>
        <Button
          variant="ghost"
          size="sm"
          disabled={selected() === undefined}
          onClick={() => setSelected(undefined)}
        >
          Reset
        </Button>
      </div>
    </div>
  )
}

Accept string labels or mixed items#

Pass a string array when the label is the value. Mix strings, item objects, and type: 'group' entries in one items list.

import { Select } from 'moraine'
import type { SelectT } from 'moraine'

const MIXED_REGIONS: SelectT.Entry[] = [
  'us-east-1',
  { value: 'eu-west-1', label: 'eu-west-1', description: 'Ireland' },
  {
    type: 'group',
    label: 'Asia Pacific',
    items: ['ap-northeast-1', { value: 'ap-south-1', label: 'ap-south-1', disabled: true }],
  },
]

export function StringItems() {
  return (
    <div class="flex flex-col gap-3 max-w-xs w-full">
      <Select
        aria-label="Deploy region"
        items={['us-east-1', 'eu-west-1', 'ap-northeast-1']}
        defaultValue="us-east-1"
        clearable
      />
      <Select
        aria-label="Deploy region with groups"
        items={MIXED_REGIONS}
        placeholder="Choose a region..."
        clearable
      />
    </div>
  )
}

Custom option and empty state renderers#

Use itemRender to customize row content with badges or status details. Use emptyRender to render a message or recovery action when items is empty.

import { Button, Select } from 'moraine'
import type { SelectT } from 'moraine'
import { createSignal } from 'solid-js'

interface FrameworkItem extends SelectT.Item {
  badge: string
}

const FRAMEWORKS: FrameworkItem[] = [
  { label: 'SolidJS', value: 'solid', badge: 'Reactive' },
  { label: 'Vue.js', value: 'vue', badge: 'Template' },
  { label: 'React', value: 'react', badge: 'Virtual DOM' },
]

export function CustomRender() {
  const [items, setItems] = createSignal<FrameworkItem[]>(FRAMEWORKS)

  return (
    <div class="max-w-xs w-full space-y-3">
      <Select<FrameworkItem>
        placeholder="Choose framework..."
        items={items()}
        defaultValue="solid"
        itemRender={(props) => (
          <div class="flex w-full items-center justify-between">
            <span>{props.item.label}</span>
            <span class="text-xs text-muted-foreground font-mono px-1.5 py-0.5 rounded bg-muted">
              {props.item.badge}
            </span>
          </div>
        )}
        emptyRender={(props) => (
          <div class="p-3 text-center space-y-2">
            <p class="text-sm text-muted-foreground">No options available.</p>
            <Button
              size="xs"
              variant="outline"
              onClick={() => {
                setItems(FRAMEWORKS)
                props.close()
              }}
            >
              Restore options
            </Button>
          </div>
        )}
      />
      <div class="flex justify-end">
        <Button
          size="xs"
          variant="ghost"
          onClick={() => setItems(items().length > 0 ? [] : FRAMEWORKS)}
        >
          Toggle empty list
        </Button>
      </div>
    </div>
  )
}

API Reference#

Attributes#

Attributes
data-closed
Slot: select-controlselect-contentselect-trigger
Description: Present when disclosure or transition content is closed.
data-disabled
Slot: select-controlselect-itemselect-trigger
Description: Present when the component, slot, or item is disabled.
data-expanded
Slot: select-controlselect-contentselect-trigger
Description: Present when the panel, accordion, or menu is expanded.
data-invalid
Slot: select-controlselect-trigger
Description: Present when the field or form has a validation error.
data-readonly
Slot: select-control
Description: Present when the field is in read-only mode.
data-required
Slot: select-control
Description: Present when the field input is required.
data-side
Slot: select-content
Description: Stores the resolved floating or drawer content side.
data-highlighted
Slot: select-itemselect-item-description
Description: Present when the item is highlighted by pointer or keyboard navigation.
data-selected
Slot: select-item
Description: Present when the item or tab is selected.
data-loading
Slot: select-trailing
Description: Present when the component or async operation is loading.
data-placeholder
Slot: select-value
Description: Present while placeholder content is displayed.

Props#

Renders a <div> element by default.

Prop