# Native Select

A styled native HTML select element with consistent design system integration.

Source: https://webjs.dev/ui/docs/components/native-select

```ts
import { html } from '@webjsdev/core';
import {
  nativeSelectWrapperClass, nativeSelectClass, nativeSelectIconClass,
} from '#components/ui/native-select.ts';
import { ChevronDownIcon } from '#lib/ui/lucide.ts';

export default function NativeSelectDemo() {
  return html`
    <div data-slot="native-select-wrapper" data-size="default" class=${nativeSelectWrapperClass()}>
      <select data-slot="native-select" data-size="default" aria-label="Status" class=${nativeSelectClass()}>
        <option data-slot="native-select-option" value="">Select status</option>
        <option data-slot="native-select-option" value="todo">Todo</option>
        <option data-slot="native-select-option" value="in-progress">In Progress</option>
        <option data-slot="native-select-option" value="done">Done</option>
        <option data-slot="native-select-option" value="cancelled">Cancelled</option>
      </select>
      ${ChevronDownIcon(nativeSelectIconClass())}
    </div>
  `;
}
```

For a styled select component, see the [Select](https://webjs.dev/ui/docs/components/select) component.

## Installation

```bash
npx @webjsdev/ui add native-select
```

### Copy and paste the following code into your project.

````ts title="components/ui/native-select.ts"
/**
 * NativeSelect: styled native `<select>`. Tier-1 class helpers. Uses
 * `appearance: none` to hide the platform chevron and overlays an SVG
 * chevron on top. Best mobile UX (native picker), full keyboard support,
 * form submission works natively. No JS.
 *
 * shadcn parity:
 *   NativeSelect             → nativeSelectClass()
 *   NativeSelect wrapper     → nativeSelectWrapperClass()
 *   NativeSelect chevron     → nativeSelectIconClass()
 *   NativeSelect option      → bare <option> (or nativeSelectOptionClass()
 *                              for explicit overrides, since the theme
 *                              stylesheet sets Canvas / CanvasText on
 *                              every <option> automatically)
 *
 * The theme stylesheet forces Canvas / CanvasText on every <option> so the
 * dropdown reads in both light and dark themes regardless of OS preference.
 * It arrives with the design tokens (`npx @webjsdev/ui init`, or `add`, which
 * writes the block when it is missing), so it is in the first paint and works
 * with JavaScript off. Advanced overrides use `nativeSelectOptionClass()` and
 * `nativeSelectOptGroupClass()`.
 *
 * Design tokens used: --input, --background, --primary, --primary-foreground,
 * --muted-foreground, --ring, --destructive.
 *
 * A11y (required for accessible output):
 *   LABEL IT. A `<label class=${labelClass()} for="<the select's id">` linked by
 *   the `for` / `id` pair is the whole requirement. A `<select>` with no label
 *   announces only its current value, so the user hears "Basic" with no idea it
 *   is the billing plan.
 *   The chevron is DECORATIVE and must stay `aria-hidden="true"`. It duplicates
 *   information the select's own role already conveys, and it sits outside the
 *   control, so without the attribute it is announced as a stray graphic.
 *   There is no placeholder option in a `<select>`. If you need one, use a
 *   `<option value="" disabled selected>` prompt, and keep `required` on the
 *   select so an empty submit is caught natively.
 *   Group long option lists with `<optgroup label="...">`; the label is
 *   announced, so it is real structure rather than only a visual break.
 *   Being native is the accessibility win here: the platform picker, the
 *   keyboard behaviour, and the mobile UX come for free. Do not rebuild it as a
 *   div-based listbox to gain styling.
 *
 * @example
 * ```html
 * <div class=${fieldClass()}>
 *   <label class=${labelClass()} for="plan">Billing plan</label>
 *   <div class=${nativeSelectWrapperClass()}>
 *     <select class=${nativeSelectClass()} name="plan" id="plan" required>
 *       <option value="" disabled selected>Choose a plan</option>
 *       <option value="basic">Basic</option>
 *       <option value="pro">Pro</option>
 *     </select>
 *     <!-- chevron icon, decorative -->
 *     <svg class="${nativeSelectIconClass()}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="m6 9 6 6 6-6" /></svg>
 *   </div>
 * </div>
 * ```
 */
import { cn } from '../lib/utils.ts';

export type NativeSelectSize = 'default' | 'sm';

// The <option> / <optgroup> colour rule is NOT injected from here. It lives in
// the theme stylesheet the kit installs, so it is in the first paint, works
// with JavaScript off, and does not make this module client-effecting (a
// module-scope call pins every page that imports it, #1320). See the
// `select option, select optgroup` rule in the theme block.
//
// `nativeSelectOptionClass()` and `nativeSelectOptGroupClass()` stay exported
// for users who want to opt into the same colours via a class helper. They
// emit the same `bg-[Canvas] text-[CanvasText]` utilities: redundant when the
// theme block is present, harmless, and they match the broader shadcn
// convention that every part has a class helper.

export const nativeSelectWrapperClass = (): string =>
  'group/native-select relative w-fit has-[select:disabled]:opacity-50';

export function nativeSelectClass(): string {
  return cn(
    'h-9 w-full min-w-0 appearance-none rounded-md border border-input bg-transparent px-3 py-2 pe-9 text-sm shadow-xs transition-[color,box-shadow] selection:bg-primary selection:text-primary-foreground placeholder:text-muted-foreground data-[size=sm]:h-8 data-[size=sm]:py-1 dark:bg-input/30 dark:hover:bg-input/50 outline-none disabled:pointer-events-none disabled:cursor-not-allowed',
    'focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50',
    'aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40',
  );
}

export const nativeSelectIconClass = (): string =>
  'top-1/2 end-3.5 size-4 -translate-y-1/2 text-muted-foreground opacity-50 pointer-events-none absolute select-none';

/** Option / optgroup styling: forces themed background even in dark mode. */
export const nativeSelectOptionClass = (): string => 'bg-[Canvas] text-[CanvasText]';
export const nativeSelectOptGroupClass = (): string => 'bg-[Canvas] text-[CanvasText]';
````

### Update the import paths to match your project setup.

## Usage

```ts
import {
  nativeSelectWrapperClass,
  nativeSelectClass,
  nativeSelectIconClass,
} from '#components/ui/native-select.ts';
```

```ts
<div class=${nativeSelectWrapperClass()}>
  <select class=${nativeSelectClass()} aria-label="Fruit">
    <option value="">Select a fruit</option>
    <option value="apple">Apple</option>
    <option value="banana">Banana</option>
    <option value="blueberry">Blueberry</option>
    <option value="pineapple">Pineapple</option>
  </select>
  <svg class=${nativeSelectIconClass()} viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="m6 9 6 6 6-6" /></svg>
</div>
```

## Composition

### Simple

Options placed directly under the `<select>` (no `<optgroup>`).

```text
nativeSelectWrapperClass()
├── nativeSelectClass() on <select>
│   ├── <option>
│   ├── <option>
│   ├── <option>
│   └── <option>
└── nativeSelectIconClass() on the chevron
```

### With groups

Use a native `<optgroup>` to organize options into categories.

```text
nativeSelectWrapperClass()
├── nativeSelectClass() on <select>
│   ├── <optgroup>
│   │   ├── <option>
│   │   └── <option>
│   └── <optgroup>
│       ├── <option>
│       └── <option>
└── nativeSelectIconClass() on the chevron
```

## Groups

Use a native `<optgroup>` to organize options into categories.

```ts
import { html } from '@webjsdev/core';
import {
  nativeSelectWrapperClass, nativeSelectClass, nativeSelectIconClass,
} from '#components/ui/native-select.ts';
import { ChevronDownIcon } from '#lib/ui/lucide.ts';

export default function NativeSelectGroups() {
  return html`
    <div data-slot="native-select-wrapper" data-size="default" class=${nativeSelectWrapperClass()}>
      <select data-slot="native-select" data-size="default" aria-label="Department" class=${nativeSelectClass()}>
        <option data-slot="native-select-option" value="">Select department</option>
        <optgroup data-slot="native-select-optgroup" label="Engineering">
          <option data-slot="native-select-option" value="frontend">Frontend</option>
          <option data-slot="native-select-option" value="backend">Backend</option>
          <option data-slot="native-select-option" value="devops">DevOps</option>
        </optgroup>
        <optgroup data-slot="native-select-optgroup" label="Sales">
          <option data-slot="native-select-option" value="sales-rep">Sales Rep</option>
          <option data-slot="native-select-option" value="account-manager">Account Manager</option>
          <option data-slot="native-select-option" value="sales-director">Sales Director</option>
        </optgroup>
        <optgroup data-slot="native-select-optgroup" label="Operations">
          <option data-slot="native-select-option" value="support">Customer Support</option>
          <option data-slot="native-select-option" value="product-manager">Product Manager</option>
          <option data-slot="native-select-option" value="ops-manager">Operations Manager</option>
        </optgroup>
      </select>
      ${ChevronDownIcon(nativeSelectIconClass())}
    </div>
  `;
}
```

## Disabled

Add the `disabled` attribute to the `<select>` to disable it. The wrapper dims itself while its select is disabled.

```ts
import { html } from '@webjsdev/core';
import {
  nativeSelectWrapperClass, nativeSelectClass, nativeSelectIconClass,
} from '#components/ui/native-select.ts';
import { ChevronDownIcon } from '#lib/ui/lucide.ts';

export default function NativeSelectDisabled() {
  return html`
    <div data-slot="native-select-wrapper" data-size="default" class=${nativeSelectWrapperClass()}>
      <select data-slot="native-select" data-size="default" aria-label="Fruit" disabled class=${nativeSelectClass()}>
        <option data-slot="native-select-option" value="">Disabled</option>
        <option data-slot="native-select-option" value="apple">Apple</option>
        <option data-slot="native-select-option" value="banana">Banana</option>
        <option data-slot="native-select-option" value="blueberry">Blueberry</option>
      </select>
      ${ChevronDownIcon(nativeSelectIconClass())}
    </div>
  `;
}
```

## Invalid

Use `aria-invalid` to show validation errors and the `data-invalid` attribute on the [Field](https://webjs.dev/ui/docs/components/field) wrapper for styling.

```ts
import { html } from '@webjsdev/core';
import {
  nativeSelectWrapperClass, nativeSelectClass, nativeSelectIconClass,
} from '#components/ui/native-select.ts';
import { ChevronDownIcon } from '#lib/ui/lucide.ts';

export default function NativeSelectInvalid() {
  return html`
    <div data-slot="native-select-wrapper" data-size="default" class=${nativeSelectWrapperClass()}>
      <select data-slot="native-select" data-size="default" aria-label="Fruit" aria-invalid="true" class=${nativeSelectClass()}>
        <option data-slot="native-select-option" value="">Error state</option>
        <option data-slot="native-select-option" value="apple">Apple</option>
        <option data-slot="native-select-option" value="banana">Banana</option>
        <option data-slot="native-select-option" value="blueberry">Blueberry</option>
      </select>
      ${ChevronDownIcon(nativeSelectIconClass())}
    </div>
  `;
}
```

## Native Select vs Select

- Use Native Select for native browser behavior, better performance, or mobile-optimized dropdowns.
- Use [Select](https://webjs.dev/ui/docs/components/select) for custom styling, animations, or complex interactions.

## RTL

To enable RTL support, see the [RTL configuration guide](https://webjs.dev/ui/docs/rtl).

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import {
  nativeSelectWrapperClass, nativeSelectClass, nativeSelectIconClass,
} from '#components/ui/native-select.ts';
import { ChevronDownIcon } from '#lib/ui/lucide.ts';

// shadcn's demo switches language with a selector; the page shows its
// default, Arabic. Its RTL build turns the style's physical padding and
// chevron position into logical ones, so the rtl: classes do that here.
const translations = {
  en: {
    dir: 'ltr',
    values: { placeholder: 'Select status', todo: 'Todo', inProgress: 'In Progress', done: 'Done', cancelled: 'Cancelled' },
  },
  ar: {
    dir: 'rtl',
    values: { placeholder: 'اختر الحالة', todo: 'مهام', inProgress: 'قيد التنفيذ', done: 'منجز', cancelled: 'ملغي' },
  },
  he: {
    dir: 'rtl',
    values: { placeholder: 'בחר סטטוס', todo: 'לעשות', inProgress: 'בתהליך', done: 'הושלם', cancelled: 'בוטל' },
  },
};

export default function NativeSelectRtl() {
  const { dir, values: t } = translations.ar;
  return html`
    <div data-slot="native-select-wrapper" data-size="default" class=${nativeSelectWrapperClass()}>
      <select data-slot="native-select" data-size="default" dir=${dir} aria-label=${t.placeholder} class=${cn(nativeSelectClass(), 'rtl:pr-2.5 rtl:pl-8')}>
        <option data-slot="native-select-option" value="">${t.placeholder}</option>
        <option data-slot="native-select-option" value="todo">${t.todo}</option>
        <option data-slot="native-select-option" value="in-progress">${t.inProgress}</option>
        <option data-slot="native-select-option" value="done">${t.done}</option>
        <option data-slot="native-select-option" value="cancelled">${t.cancelled}</option>
      </select>
      ${ChevronDownIcon(cn(nativeSelectIconClass(), 'rtl:right-auto rtl:left-2.5'))}
    </div>
  `;
}
```

## API Reference

### nativeSelectClass

The classes for the native `<select>` element. It hides the platform chevron, so wrap the select in an element with `nativeSelectWrapperClass()` and put the chevron icon after it with `nativeSelectIconClass()`. The chevron is decorative, so keep `aria-hidden="true"` on it. Every native attribute (`name`, `required`, `disabled`, `multiple`) works as usual, and the select submits with its form with no script.

| Helper | Applies to |
| --- | --- |
| `nativeSelectWrapperClass()` | The wrapper around the select and its chevron. Set `data-size="sm"` on the wrapper and the select for the small size. |
| `nativeSelectClass()` | The `<select>` element. |
| `nativeSelectIconClass()` | The chevron icon. |

```ts
<div class=${nativeSelectWrapperClass()}>
  <select class=${nativeSelectClass()} aria-label="Option">
    <option value="option1">Option 1</option>
    <option value="option2">Option 2</option>
  </select>
  <svg class=${nativeSelectIconClass()} viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="m6 9 6 6 6-6" /></svg>
</div>
```

### nativeSelectOptionClass

An individual option is a native `<option>`. The theme stylesheet already gives every option the themed colours, so a bare `<option>` needs no class; `nativeSelectOptionClass()` applies the same colours explicitly.

| Attribute | Type | Default |
| --- | --- | --- |
| `value` | `string` |  |
| `disabled` | `boolean` | `false` |

### nativeSelectOptGroupClass

Groups related options together with a native `<optgroup>`. Its label is announced, so it is real structure rather than only a visual break. Like options, it takes the themed colours with no class; `nativeSelectOptGroupClass()` applies them explicitly.

| Attribute | Type | Default |
| --- | --- | --- |
| `label` | `string` |  |
| `disabled` | `boolean` | `false` |

```ts
<optgroup label="Fruits">
  <option value="apple">Apple</option>
  <option value="banana">Banana</option>
</optgroup>
```
