Skip to Content
Cristal

Forms

Select

Choose one value among several.

<cr-select>CrSelect

Example

Options are written as in HTML, with child <option> elements (disabled for an unavailable option). They can be added or removed at any time, for example from a .map() in React.

import { CrSelect } from '@cristal-ui/react';

export default function SelectBasic() {
  return (
    <CrSelect label="Category" name="category" placeholder="Choose a category" hint="The category sets the tax rate.">
      <option value="book">Books</option>
      <option value="food">Groceries</option>
      <option value="tech">Electronics</option>
      <option value="old" disabled>
        Archived
      </option>
    </CrSelect>
  );
}

Multiple selection

With multiple, each option shows a checkbox and the list stays open while selecting. Values are read and set with values (an array), and onCrChange gives the array in event.detail. The form submits each value under the same name, like a native <select multiple>: read them with formData.getAll('languages').

Values: ["en"]
'use client';

import { useState } from 'react';
import { CrSelect } from '@cristal-ui/react';

export default function SelectMultiple() {
  const [languages, setLanguages] = useState<string[]>(['en']);

  return (
    <>
      <CrSelect
        label="Languages spoken"
        name="languages"
        placeholder="Choose languages"
        multiple
        values={languages}
        onCrChange={(event) => setLanguages(event.detail as string[])}
      >
        <option value="en">English</option>
        <option value="fr">French</option>
        <option value="es">Spanish</option>
        <option value="de">German</option>
      </CrSelect>
      <output>Values: {JSON.stringify(languages)}</output>
    </>
  );
}

With searchable, a search field appears at the top of the open list and filters options as you type, ignoring accents and case: "ev" finds "Évry". In each option, the letters that match the search turn bold, in the theme colour (::part(match) to style them). Typing on the closed list opens it directly with the search filled in. searchable can be combined with multiple.

import { CrSelect } from '@cristal-ui/react';

const cities = ['Austin', 'Boston', 'Chicago', 'Denver', 'London', 'Manchester', 'Montréal', 'New York', 'Québec', 'Seattle'];

export default function SelectSearchable() {
  return (
    <>
      <CrSelect label="City" name="city" placeholder="Choose a city" searchable>
        {cities.map((city) => (
          <option key={city} value={city}>
            {city}
          </option>
        ))}
      </CrSelect>
      <CrSelect label="Skills" name="skills" placeholder="Choose skills" multiple searchable>
        {['Accessibility', 'Animation', 'CSS', 'Design system', 'React', 'Testing', 'TypeScript', 'Web Components'].map((skill) => (
          <option key={skill} value={skill}>
            {skill}
          </option>
        ))}
      </CrSelect>
    </>
  );
}

When options come from an API, add remote to searchable. The list no longer filters anything itself: it emits onCrSearch with the typed text (event.detail), 300 ms after the last keystroke so the API is not called on every letter, and shows exactly the <option> elements you give it. During the call, loading shows and announces "Searching…".

  • On close, the search is cleared and onCrSearch is emitted with an empty text: restore your default options then.
  • Selected options keep their label in the button even when they are no longer part of the results, including with multiple.
  • Ignore responses that arrive out of order: only the latest search counts (see latest in the example).

The example queries the French public API of municipalities (geo.api.gouv.fr), by name or by postal code.

'use client';

import { useRef, useState } from 'react';
import { CrSelect } from '@cristal-ui/react';

type Commune = { code: string; nom: string };

const popular: Commune[] = [
  { code: '75056', nom: 'Paris' },
  { code: '13055', nom: 'Marseille' },
  { code: '69123', nom: 'Lyon' },
  { code: '31555', nom: 'Toulouse' },
];

const fetchCommunes = async (query: string): Promise<Commune[]> => {
  const filter = /^\d+$/.test(query) ? `codePostal=${query}` : `nom=${encodeURIComponent(query)}`;
  const response = await fetch(`https://geo.api.gouv.fr/communes?${filter}&fields=nom,code&limit=8`);
  return response.ok ? response.json() : [];
};

export default function SelectRemote() {
  const [communes, setCommunes] = useState(popular);
  const [loading, setLoading] = useState(false);
  const latest = useRef('');

  const search = async (query: string) => {
    latest.current = query;
    if (!query) {
      setLoading(false);
      return setCommunes(popular);
    }
    setLoading(true);
    const found = await fetchCommunes(query).catch(() => []);
    if (latest.current !== query) return; // a newer search is in progress
    setCommunes(found);
    setLoading(false);
  };

  return (
    <CrSelect
      label="French town"
      name="commune"
      hint="Name or postcode"
      placeholder="Choose a town"
      searchable
      remote
      loading={loading}
      onCrSearch={(event) => search(event.detail)}
    >
      {communes.map((commune) => (
        <option key={commune.code} value={commune.code}>
          {commune.nom}
        </option>
      ))}
    </CrSelect>
  );
}

By default, without these properties, the list stays a simple list without search.

Animations

Like the menu, the list accepts an animation property: fade (default), anchor-pop, turn-over, card-deal, drum-roll, outline-trace or tile-build.

import { CrSelect } from '@cristal-ui/react';

export default function SelectAnimated() {
  return (
    <CrSelect label="Display as" value="list" animation="drum-roll">
      <option value="list">List</option>
      <option value="grid">Grid</option>
      <option value="board">Board</option>
    </CrSelect>
  );
}

Keyboard

KeyList closedList open
Down / Up Arrowopens the listnext / previous option
Enter, Spaceopens the listselects the option and closes
Home / End—first / last option
Lettersopens and moves to the option starting with those lettersmoves to the matching option
Escape—closes without changing the value
Enter, Space (with multiple)—checks or unchecks the option, the list stays open
Tabmoves to the next fieldselects the option and moves to the next field

Validation

With required, form submission is blocked until an option is chosen, and the message "Choose an option from the list." is shown ("Choose at least one option from the list." with multiple). The error property replaces this message.

error-animation animates the error when it appears and on every rejected submit (zigzag, badge, echo…): see Animated error.

Accessibility

  • Follows the W3C "combobox" pattern (ARIA Authoring Practices): focus stays on the field, and the active option is announced through aria-activedescendant.

  • The label, hint and error are read by screen readers, as for the text field.

  • The list is displayed above the page: it is never clipped by a scrolling container or a modal, and opens upward when there is not enough room below.

  • Clicking outside the list closes it.

  • With multiple, the list is announced as "multi-selectable" (aria-multiselectable) and each option as checked or not.

  • With searchable, the search field is labeled "Search the list", the active option is still announced while typing, and "No results" is read when nothing matches. In the field, Space types a space: select with Enter.

  • With remote, the list is marked busy (aria-busy) during loading, and "Searching…" is read.

API

Properties

PropertyTypeDefaultDescription
animation"anchor-pop" | "card-deal" | "drum-roll" | "fade" | "outline-trace" | "tile-build" | "turn-over"'fade'Animation d'ouverture et de fermeture de la liste.
disabledbooleanfalseDésactive la liste.
errorstring—Message d'erreur ; remplace le message automatique de validation.
errorAnimation"drop" | "echo" | "jitter" | "none" | "pop" | "wobble" | "zigzag"'none'Animation de l'erreur quand elle apparaît et à chaque envoi refusé : none (par défaut), zigzag, pop, drop, echo, jitter ou wobble.
hintstring—Texte d'aide, lu par les lecteurs d'écran.
label (obligatoire)string—Libellé affiché au-dessus de la liste.
loadingbooleanfalseAffiche « Recherche en cours… » pendant le chargement des options (avec remote).
multiplebooleanfalsePermet de choisir plusieurs options.
namestring—Nom envoyé avec le formulaire.
placeholderstring—Texte affiché tant qu'aucune option n'est choisie.
remotebooleanfalseRecherche côté serveur (avec searchable) : pas de filtre local, l'application remplace les options à chaque crSearch.
requiredbooleanfalseRend le choix obligatoire.
searchablebooleanfalseAjoute un champ de recherche en haut de la liste.
valuestring''Valeur de l'option sélectionnée (liste simple).
valuesstring[][]Valeurs des options sélectionnées (avec multiple).

Events

Reactevent.detailDescription
onCrChangestring | string[]Émis quand la sélection change ; detail : la valeur, ou le tableau des valeurs avec multiple.
onCrSearchstringÉmis 300 ms après la dernière frappe dans la recherche (avec remote) ; detail : le texte recherché.

CSS parts

To style it from outside: cr-select::part(name) { … }

PartDescription
controlLe bouton qui ouvre la liste.
errorLe message d'erreur.
hintLe texte d'aide.
labelLe libellé.
listboxLa liste des options.
matchLes lettres d'une option qui correspondent à la recherche.
optionUne option.
searchLe champ de recherche (avec searchable).

On this page