Ir al contenido

Combobox

Una caja de texto con una lista debajo: la persona escribe unas letras y la lista deja solo lo que coincide. Para listas largas donde desplazarse tomaría mucho.

import { Combobox } from '@sypnia/ui/react'

En esta página
  1. Escribir para filtrar
  2. Nada coincide
  3. Opciones desde un servidor
  4. Estados
  5. Cuándo usarlo
  6. Para todos
  7. Props

Escribir para filtrar

Escribe «ord» o «log»: la lista se reduce a las tablas que lo contienen.

Every row of orders goes into one CSV file.

Código
import { useState } from 'react';
import { Combobox, Field, FormGrid, type Option } from '@sypnia/ui/react';

const tables: Option[] = [
  { value: 'customers', label: 'customers', description: '12,480 rows', icon: 'table' },
  { value: 'orders', label: 'orders', description: '98,204 rows', icon: 'table' },
  { value: 'order_items', label: 'order_items', description: '311,930 rows', icon: 'table' },
  { value: 'products', label: 'products', description: '642 rows', icon: 'table' },
  { value: 'invoices', label: 'invoices', description: '40,112 rows', icon: 'table' },
  { value: 'audit_log', label: 'audit_log', description: '2,904,551 rows', icon: 'table' },
  { value: 'sessions', label: 'sessions', description: '77,310 rows', icon: 'table' },
];

export default function Basic() {
  const [table, setTable] = useState<string | null>('orders');
  return (
    <FormGrid>
      <Field label="Table to export" hint={table ? `Every row of ${table} goes into one CSV file.` : 'Type a few letters of its name.'}>
        <Combobox options={tables} value={table} onChange={setTable} placeholder="Find a table" />
      </Field>
    </FormGrid>
  );
}

Nada coincide

Escribe «zebra». La lista dice que no hay nada, y qué hacer.

Código
import { Combobox, Field, FormGrid, type Option } from '@sypnia/ui/react';

const members: Option[] = [
  { value: 'laura', label: 'Laura Méndez', description: 'laura@northwind.dev' },
  { value: 'diego', label: 'Diego Ruiz', description: 'diego@northwind.dev' },
  { value: 'ana', label: 'Ana Torres', description: 'ana@northwind.dev' },
];

export default function Empty() {
  return (
    <FormGrid>
      <Field label="Assign to">
        <Combobox options={members} placeholder="Find a member" emptyText="Nobody in this project has that name. Invite them from the team page first." />
      </Field>
    </FormGrid>
  );
}

Opciones desde un servidor

Cada letra le pregunta a un servidor (de mentira). Mientras viaja la respuesta, la lista muestra filas de skeleton, nunca una rueda de carga.

Reports and backups use this time.

Código
import { useEffect, useState } from 'react';
import { Combobox, Field, FormGrid, type Option } from '@sypnia/ui/react';

const zones = ['America/Bogota', 'America/Lima', 'America/Mexico_City', 'America/New_York', 'America/Sao_Paulo', 'Europe/Dublin', 'Europe/Madrid', 'Europe/Berlin', 'Asia/Singapore', 'Asia/Tokyo'];

// Stands in for a request: answers after a moment with the zones that contain the text.
const search = (text: string) => new Promise<Option[]>((resolve) => {
  setTimeout(() => resolve(zones.filter((z) => z.toLowerCase().includes(text.toLowerCase())).map((z) => ({ value: z, label: z.replace('_', ' ') }))), 900);
});

export default function Loading() {
  const [text, setText] = useState('');
  const [options, setOptions] = useState<Option[]>([]);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    let current = true;
    setLoading(true);
    void search(text).then((found) => { if (current) { setOptions(found); setLoading(false); } });
    return () => { current = false; };
  }, [text]);
  return (
    <FormGrid>
      <Field label="Time zone" hint="Reports and backups use this time.">
        <Combobox options={options} loading={loading} filter={false} onInputChange={setText} placeholder="Find a city" />
      </Field>
    </FormGrid>
  );
}

Estados

Con un error que dice cómo arreglarlo, y desactivado.

Choose a table from the list: «ordrs» does not exist in this database.

This project has one database.

Código
import { Combobox, Field, FormGrid, type Option } from '@sypnia/ui/react';

const tables: Option[] = [{ value: 'orders', label: 'orders' }, { value: 'customers', label: 'customers' }, { value: 'invoices', label: 'invoices' }];

export default function States() {
  return (
    <FormGrid>
      <Field label="Table to export" error="Choose a table from the list: «ordrs» does not exist in this database.">
        <Combobox options={tables} placeholder="Find a table" />
      </Field>
      <Field label="Database" hint="This project has one database.">
        <Combobox disabled options={[{ value: 'main', label: 'main' }]} defaultValue="main" />
      </Field>
    </FormGrid>
  );
}

Cuándo usarlo

Úsalo cuando

  • Una opción de una lista larga que la persona puede nombrar: una tabla, una zona horaria, un miembro, un país.
  • Las opciones vienen de un servidor mientras la persona escribe: pasa onInputChange, loading y filter={false}.
  • La lista puede volver vacía: siempre lo dice, con palabras.

No lo uses cuando

  • Hay menos de unas diez opciones: un Select las muestra todas de un vistazo.
  • La persona puede escribir cualquier cosa, no solo lo de la lista: eso es un Input (con sugerencias, un Autocomplete).
  • Se pueden elegir varias: MultiSelect.

Para todos

  • Escribir filtra; la flecha abajo abre la lista y la recorre; Enter elige; Escape cierra la lista, y un segundo Escape borra lo escrito.
  • Se anuncia como combobox; la cantidad de opciones que coinciden se anuncia cuando cambia.
  • Mientras cargan las opciones, la lista tiene filas de skeleton y se marca como ocupada. Sypnia nunca muestra una rueda de carga.
  • Dentro de un Field toma la etiqueta, la pista y el error por sí solo; suelto, dale un aria-label.

Props

ComboboxTipoPor defecto
optionsobligatorio Option[]
aria-describedby string
aria-label

The name for screen readers when there is no Field around it.

string
aria-labelledby string
className string
defaultValue string
disabled boolean
emptyText

What the list says when nothing matches.

ReactNode
filter

Set false when the options already come filtered (from a server). By default the list keeps the options that contain what was typed.

boolean true
id

Inside a Field it comes from the Field.

string
invalid

Marks the value as wrong. Inside a `<Field error>` it is set for you.

boolean
loading

Options are on their way: the list shows rows of skeleton.

boolean
name string
onChange

The chosen value, or null when the person clears the text.

((value: string | null) => void)
onInputChange

Called with what the person types: use it to ask a server for options.

((text: string) => void)
placeholder string
size "sm" | "md" | "lg"
value string | null
  1. Escribir para filtrar
  2. Nada coincide
  3. Opciones desde un servidor
  4. Estados
  5. Cuándo usarlo
  6. Para todos
  7. Props

    Busca páginas, secciones y términos