DocumentaciónSelect
Select
Una opción o varias. Siempre el valor correcto.
Primeros pasos
Instalar el paquete
Usa React 19 e importa la hoja de estilos del paquete una vez en el CSS global de tu aplicación. Los estilos incluidos están diseñados para Tailwind CSS 4.
bun add @rentnerkev/select@import '@rentnerkev/select/tailwind.css';Combobox: varios objetos y resultados asíncronos#
ComboboxProps<T> es una unión discriminada: con multiple: true, value es readonly T[] y onValueChange recibe T[]. El modo individual conserva T | null. Controla searchValue por separado y proporciona valores getOptionKey únicos y estables; los objetos seleccionados se conservan aunque lleguen nuevos arrays y objetos de resultados asíncronos, incluso si no están en la página actual. La igualdad predeterminada compara claves. filterMode external muestra los resultados proporcionados; la aplicación gestiona las consultas, el debounce, la carga, la cancelación y la creación de opciones.
import { Combobox } from '@rentnerkev/select/combobox'
import { useState, type FormEvent } from 'react'
type Customer = { id: string; name: string; email: string }
export default function CustomerTeam({
results,
loading = false,
}: {
results: readonly Customer[]
loading?: boolean
}) {
const [selected, setSelected] = useState<readonly Customer[]>([])
const [query, setQuery] = useState('')
const [submitted, setSubmitted] = useState<string[]>([])
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault()
setSubmitted(new FormData(event.currentTarget).getAll('customers').map(String))
}
return (
<form onSubmit={handleSubmit}>
<Combobox
multiple
clearable
name="customers"
label="Customer team"
value={selected}
onValueChange={setSelected}
searchValue={query}
onSearchValueChange={setQuery}
options={results}
loading={loading}
filterMode="external"
getOptionKey={(customer) => customer.id}
getOptionLabel={(customer) => customer.name}
getOptionDescription={(customer) => customer.email}
getFormValue={(customer) => customer.id}
/>
<button type="submit">Read selected IDs</button>
<output>{submitted.join(', ')}</output>
</form>
)
}Posición estable al abrir por primera vez y portales ShadowRoot#
CustomSelect y Combobox comparten la medición de ventanas emergentes y la preparación previa a su visualización. La ventana actual permanece oculta hasta medirse con las restricciones definitivas de la ventana gráfica, incluido el ancho de la barra de desplazamiento, de modo que la primera apertura tras recargar no aparece fugazmente en coordenadas antiguas. El desplazamiento, los cambios de la ventana gráfica y la sustitución del portal vuelven a medirla. Los portales ShadowRoot conservan el foco de teclado, la pérdida de foco del campo completo y el cierre al pulsar fuera.
import { CustomSelect } from '@rentnerkev/select'
import { useState } from 'react'
export default function LanguageSelect() {
const [language, setLanguage] = useState('en')
return (
<div className="flex justify-end">
<CustomSelect
label="Language"
contentWidth="content"
value={language}
onValueChange={setLanguage}
options={[
{ value: 'en', label: 'English' },
{ value: 'de', label: 'Deutsch' },
]}
/>
</div>
)
}Opciones agrupadas de Select y Combobox#
Define option.group en CustomSelect o devuelve un nombre de grupo desde Combobox.getOptionGroup. Los encabezados no se pueden seleccionar; las entradas sin grupo siguen disponibles. El filtrado, la navegación con teclado, las entradas deshabilitadas y la virtualización funcionan entre grupos. classNames.group y groupLabel personalizan la presentación.
import { useState } from 'react'
import { CustomSelect } from '@rentnerkev/select'
import { Combobox } from '@rentnerkev/select/combobox'
const roles = [
{ id: 'owner', name: 'Owner', group: 'Team' },
{ id: 'editor', name: 'Editor', group: 'Team' },
{ id: 'guest', name: 'Guest', group: 'Visitors' },
]
export default function GroupedChoices() {
const [role, setRole] = useState('editor')
const [customer, setCustomer] = useState<(typeof roles)[number] | null>(null)
const [query, setQuery] = useState('')
return (
<section className="grid gap-4">
<CustomSelect
label="Role"
options={roles.map(({ id, name, group }) => ({
value: id,
label: name,
group,
}))}
value={role}
onValueChange={setRole}
/>
<Combobox
label="Search roles"
options={roles}
value={customer}
onValueChange={setCustomer}
searchValue={query}
onSearchValueChange={setQuery}
getOptionKey={(option) => option.id}
getOptionLabel={(option) => option.name}
getOptionGroup={(option) => option.group}
/>
</section>
)
}Crear una nueva opción de Combobox#
onCreateOption añade una fila de creación cuando la búsqueda recortada no está vacía y ninguna opción existente tiene la misma etiqueta, sin distinguir mayúsculas. createOptionLabel personaliza esa fila. El callback recibe la consulta recortada; tu aplicación crea, guarda y selecciona la opción. Los controles deshabilitados o de solo lectura no pueden crear entradas.
import { useState } from 'react'
import { Combobox } from '@rentnerkev/select/combobox'
type Tag = { id: string; label: string }
export default function CreateTag() {
const [options, setOptions] = useState<Tag[]>([
{ id: 'react', label: 'React' },
])
const [value, setValue] = useState<Tag | null>(null)
const [query, setQuery] = useState('')
function createOption(label: string) {
const option = { id: crypto.randomUUID(), label }
setOptions((current) => [...current, option])
setValue(option)
setQuery('')
}
return (
<Combobox
label="Tag"
options={options}
value={value}
onValueChange={setValue}
searchValue={query}
onSearchValueChange={setQuery}
getOptionKey={(option) => option.id}
getOptionLabel={(option) => option.label}
onCreateOption={createOption}
createOptionLabel={(label) => 'Create tag: ' + label}
/>
)
}Quitar elementos seleccionados individualmente#
Activa removableSelectedItems en un CustomSelect múltiple para quitar valores sin abrir el desplegable. Su valor predeterminado es false. Al pasar el cursor o enfocar con teclado aparecen un tachado rojo y una ayuda localizada; un clic, Intro o Espacio quita solo ese valor. Las opciones deshabilitadas permanecen fijas. disabled, readOnly y un renderValue propio ocultan estos controles.
import { useState } from 'react'
import { CustomSelect } from '@rentnerkev/select'
export default function RemoveSelectedRoles() {
const [values, setValues] = useState<string[]>(['editor', 'locked'])
return (
<CustomSelect
label="Roles"
name="roles"
multiple
clearable
removableSelectedItems
value={values}
onValueChange={setValues}
options={[
{ value: 'editor', label: 'Editor' },
{ value: 'reviewer', label: 'Reviewer' },
{ value: 'locked', label: 'Required role', disabled: true },
]}
messages={{
clickToRemove: 'Click to remove',
removeSelectedItem: (label) => 'Remove ' + label,
}}
/>
)
}Select 6.0: migración al menú nativo#
La versión 6.0.0 sustituye Radix Select por un menú React/DOM. Los imports y las props de los componentes no cambian. El menú no es modal: Tab y Mayús+Tab lo cierran y recorren los controles del formulario; los clics externos lo cierran y activan su destino. Escape y la selección individual devuelven el foco al disparador. Las opciones, incluido renderOption, solo se montan al abrir; la búsqueda por teclado con el menú cerrado usa option.label.
import { CustomSelect } from '@rentnerkev/select'
import { useState } from 'react'
export default function NativeSelect() {
const [value, setValue] = useState('standard')
return (
<CustomSelect
label="Delivery"
onValueChange={setValue}
options={[
{ value: 'standard', label: 'Standard' },
{ value: 'express', label: 'Express' },
]}
value={value}
/>
)
}Combobox: resultados de búsqueda externos#
Nuevo en 5.2.0: Combobox<T> acepta objetos de tu dominio con getOptionKey y getOptionLabel únicos y estables. value y searchValue son independientes: escribir cambia solo la consulta y seleccionar cambia solo el valor. Actualiza ambos al seleccionar si la etiqueta debe sustituir a la consulta. filterMode es external por defecto y muestra los resultados recibidos sin cambios; local activa el filtrado por etiqueta. Tu aplicación gestiona peticiones, debounce y cancelación. La selección persiste al cambiar la página de resultados. loading oculta resultados anteriores; loadingText, emptyText y messages.loading personalizan el estado.
import { Combobox } from '@rentnerkev/select/combobox'
import { useState } from 'react'
type Customer = { id: string; name: string; email: string }
export default function CustomerSearch({
results,
loading = false,
}: {
results: readonly Customer[]
loading?: boolean
}) {
const [customer, setCustomer] = useState<Customer | null>(null)
const [query, setQuery] = useState('')
return (
<Combobox
clearable
filterMode="external"
getOptionDescription={(option) => option.email}
getOptionKey={(option) => option.id}
getOptionLabel={(option) => option.name}
getFormValue={(option) => option.id}
label="Customer"
loading={loading}
name="customerId"
onSearchValueChange={setQuery}
onValueChange={(next) => {
setCustomer(next)
setQuery(next?.name ?? '')
}}
options={results}
searchValue={query}
value={customer}
/>
)
}Estilos de texto, ajuste y ancho emergente#
Nuevo en 5.2.0: controlSize sm/md/lg fija 36/44/48 px; omitirlo conserva la geometría existente. textOverflow usa truncate por defecto o wrap para textos largos. Un activador sin tamaño explícito puede crecer al ajustar texto; un tamaño explícito conserva su altura. contentWidth usa trigger por defecto o content, con el activador como mínimo y el viewport como máximo. Los slots optionLabel, optionDescription, optionIndicator, selectedLabel y selectedDescription evitan selectores descendientes. Los slots sustituyen estilos visuales; los proveedores anidados heredan cada uno y una cadena vacía elimina un valor por defecto. Combobox usa search para la entrada y, en su ausencia, trigger.
import { CustomSelect, SelectProvider } from '@rentnerkev/select'
import { useState } from 'react'
export default function Delivery() {
const [value, setValue] = useState('standard')
return (
<SelectProvider
contentWidth="content"
portalClassName="font-sans"
portalZIndex={12000}
textOverflow="wrap"
classNames={{
optionLabel: 'font-semibold',
selectedLabel: 'text-sky-700',
}}
>
<CustomSelect
label="Delivery"
onValueChange={setValue}
options={[
{
value: 'standard',
label: 'Standard delivery with shipment tracking',
subOption: 'Three business days',
},
{
value: 'express',
label: 'Express delivery',
subOption: 'Next business day',
},
]}
value={value}
/>
</SelectProvider>
)
}Adaptador de formulario sin interfaz#
getSelectFieldProps de /form conecta campos estructurales con CustomSelect o Combobox sin importar React ni runtime de formularios. Devuelve name, value, onValueChange, onBlur del campo completo y error. Los errores aparecen tras tocar el campo por defecto; errorVisibility acepta touched, always o never. getReadableSelectError acepta cadenas u objetos con message de tipo cadena; mapError procesa otros formatos. Un error null deja intencionadamente la validación al formulario. Llama a la función dentro de un render suscrito; Combobox sigue necesitando sus propios manejadores de searchValue.
import { CustomSelect } from '@rentnerkev/select'
import {
getReadableSelectError,
getSelectFieldProps,
} from '@rentnerkev/select/form'
import type { SelectFormField } from '@rentnerkev/select/form'
export default function RegionField({
field,
}: {
field: SelectFormField<string>
}) {
return (
<CustomSelect
{...getSelectFieldProps(field, {
errorVisibility: 'touched',
mapError: getReadableSelectError,
})}
label="Region"
options={[{ value: 'eu', label: 'Europe' }]}
/>
)
}Herramientas locales de IA: metadatos y guías#
Importa la entrada /ai en un script local de Node.js o Bun. Estas herramientas síncronas de solo lectura usan node:fs para leer el paquete instalado sin importar su interfaz. getPackageInfo() devuelve PackageInfo con la versión instalada, las exportaciones públicas y las dependencias pares. getPackageDocumentation() devuelve un PackageDocument con path y content; el valor predeterminado es usage, y readme selecciona README.md. Solo se aceptan estos dos documentos incluidos. Los resultados describen tu versión instalada, que puede diferir de este sitio web.
import { getPackageDocumentation, getPackageInfo } from '@rentnerkev/select/ai'
import type { PackageDocument, PackageInfo } from '@rentnerkev/select/ai'
const info: PackageInfo = getPackageInfo()
const usage: PackageDocument = getPackageDocumentation()
const readme = getPackageDocumentation('readme')
console.log(info.name, info.version, info.exports, info.peerDependencies)
console.log(usage.path, usage.content)
console.log(readme.path, readme.content)Herramientas locales de IA: declaraciones públicas#
getPackageApi() devuelve PackageApi con package, la version instalada, los subpaths seleccionados y declarations como objetos PackageDocument. Lee las entradas públicas tipadas y sus dependencias locales de declaraciones; la propia entrada /ai queda excluida. Usa subpath, como . o ./types, para seleccionar una entrada pública. symbol comprueba que la entrada seleccionada exporta el nombre; no recorta los archivos de declaraciones a ese símbolo. Los subpaths desconocidos, los nombres no válidos y los nombres no exportados por la entrada seleccionada generan errores. No se pueden proporcionar rutas de archivo arbitrarias.
import { getPackageApi } from '@rentnerkev/select/ai'
import type { PackageApi } from '@rentnerkev/select/ai'
const api: PackageApi = getPackageApi()
const selected = getPackageApi({ subpath: '.', symbol: 'CustomSelect' })
console.log(api.package, api.version, api.subpaths)
for (const declaration of selected.declarations) {
console.log(declaration.path, declaration.content)
}Herramientas locales de IA: búsqueda y ejemplos#
searchPackageDocumentation(query) busca en README.md y docs/usage.md con una consulta literal, sin espacios en los extremos y sin distinguir mayúsculas. Devuelve objetos PackageSearchMatch con path, line numerada desde uno y el text coincidente; una consulta vacía devuelve un array vacío. getPackageExamples() devuelve cada bloque de código delimitado de la guía instalada como un PackageExample con language y code. Estas herramientas devuelven texto para tus propias herramientas; no ejecutan ejemplos ni contactan con un servicio de IA.
import { getPackageExamples, searchPackageDocumentation } from '@rentnerkev/select/ai'
import type { PackageExample, PackageSearchMatch } from '@rentnerkev/select/ai'
const matches: PackageSearchMatch[] = searchPackageDocumentation('CustomSelect')
const examples: PackageExample[] = getPackageExamples()
for (const match of matches) {
console.log(match.path, match.line, match.text)
}
for (const example of examples) {
console.log(example.language, example.code)
}CustomSelect y opciones tipadas#
Pasa options con value y label y controla la selección con value/onValueChange. TValue se infiere de los valores y puede ser una cadena, un número o un objeto. Cada opción puede incluir subOption para texto de apoyo y disabled para impedir su selección. label, description, placeholder e icon describen el campo; fallbackOption etiqueta un valor seleccionado que no aparece en la lista.
import { useState } from 'react'
import { CustomSelect } from '@rentnerkev/select'
const options = [
{ value: 'tooltips', label: 'Tooltips', subOption: 'Helpful hints' },
{ value: 'toasts', label: 'Toasts' },
{ value: 'coming-soon', label: 'Coming soon', disabled: true },
]
export default function PackageSelect() {
const [value, setValue] = useState('')
return (
<CustomSelect
label="Package"
onValueChange={setValue}
options={options}
value={value}
/>
)
}Selección múltiple y límites#
Activa multiple y usa un array de valores. onValueChange devuelve un array nuevo. minSelection y maxSelection definen los límites; maxSelection impide añadir opciones una vez alcanzado el máximo. required y error integran la validación. Las opciones deshabilitadas no se pueden seleccionar.
import { useState } from 'react'
import { CustomSelect } from '@rentnerkev/select'
const options = ['Tooltips', 'Toasts', 'Inputs'].map((name) => ({
value: name,
label: name,
}))
export default function MultiplePackages() {
const [values, setValues] = useState<string[]>([])
return (
<CustomSelect
label="Packages"
maxSelection={2}
minSelection={1}
multiple
onValueChange={setValues}
options={options}
value={values}
/>
)
}Valores borrables y emptyValue#
Para borrar directamente una selección única, usa clearable con un estado que admita null; al borrar, onValueChange emite null. emptyValue permite elegir otro marcador vacío, como una cadena vacía. El callback antiguo onClear sigue disponible cuando gestionas el borrado por separado. Una selección múltiple se borra a un array vacío.
import { useState } from 'react'
import { CustomSelect } from '@rentnerkev/select'
export default function ClearablePackage() {
const [value, setValue] = useState<string | null>(null)
return (
<CustomSelect
clearable
label="Package"
onValueChange={setValue}
options={[{ value: 'tooltips', label: 'Tooltips' }]}
value={value}
/>
)
}Búsqueda y navegación con teclado#
searchable activa el campo de búsqueda en la ventana emergente; usa false para una lista fija y corta. El control admite navegación, selección y cierre con el teclado. messages personaliza las etiquetas, el placeholder y los resultados vacíos de la búsqueda. Añade un nombre accesible aunque no muestres una etiqueta visible.
import { useState } from 'react'
import { CustomSelect } from '@rentnerkev/select'
export default function SearchablePackages() {
const [value, setValue] = useState('')
return (
<CustomSelect
label="Find a package"
messages={{
searchPlaceholder: 'Type a package name',
noResults: 'No matching package',
}}
onValueChange={setValue}
options={[
{ value: 'inputs', label: 'Inputs' },
{ value: 'calendar', label: 'Calendar' },
]}
searchable
value={value}
/>
)
}Valores de objeto e igualdad#
Si los valores son objetos, usa isOptionEqualToValue para comparar claves estables en lugar de la identidad del objeto. Así la selección se conserva cuando vuelves a cargar las opciones. getFormValue serializa un objeto para formularios nativos.
import { useState } from 'react'
import { CustomSelect } from '@rentnerkev/select'
type Package = { id: number; name: string }
const options = [{ value: { id: 1, name: 'Tooltips' }, label: 'Tooltips' }]
export default function ObjectSelect() {
const [value, setValue] = useState<Package | null>(null)
return (
<CustomSelect
clearable
getFormValue={(item) => String(item.id)}
isOptionEqualToValue={(option, selected) =>
option.id === selected.id
}
label="Package"
name="packageId"
onValueChange={setValue}
options={options}
value={value}
/>
)
}Renderizado personalizado de opciones y valores#
renderOption recibe la opción y su estado selected/disabled. renderValue recibe un array de opciones seleccionadas, incluso en modo único. Devuelve contenido de React para añadir distintivos o información secundaria sin perder la navegación con el teclado ni el comportamiento de selección.
import { useState } from 'react'
import { CustomSelect } from '@rentnerkev/select'
export default function RichOptions() {
const [value, setValue] = useState('')
return (
<CustomSelect
label="Package"
onValueChange={setValue}
options={[{ value: 'tooltips', label: 'Tooltips' }]}
renderOption={(option, state) => (
<span>
{state.selected ? '✓ ' : ''}
{option.label}
</span>
)}
renderValue={(selected) =>
selected.map((option) => option.label).join(', ')
}
value={value}
/>
)
}Formularios nativos, foco y estados del campo#
name crea valores para formularios nativos; getFormValue convierte valores personalizados en cadenas. Los campos múltiples envían valores repetidos, que puedes leer con FormData.getAll. omitEmptyFormValue omite una selección múltiple vacía. id, label, description, error, required y las props ARIA describen la validación. disabled impide la interacción; readOnly evita cambios. triggerRef enfoca el botón, onBlur registra la salida del campo y nonce aporta un nonce de CSP para los estilos del componente cuando hace falta.
import { useState } from 'react'
import { CustomSelect } from '@rentnerkev/select'
export default function PackageForm() {
const [values, setValues] = useState<string[]>([])
return (
<form
onSubmit={(event) => {
event.preventDefault()
console.log(
new FormData(event.currentTarget).getAll('packages'),
)
}}
>
<CustomSelect
label="Packages"
multiple
name="packages"
omitEmptyFormValue
onValueChange={setValues}
options={[{ value: 'inputs', label: 'Inputs' }]}
value={values}
/>
<button type="submit">Save</button>
</form>
)
}SelectProvider#
Configura locale, messages, classNames, searchable y nonce para un grupo de selectores. La configuración de cada componente tiene prioridad sobre el proveedor más cercano.
import { useState } from 'react'
import { CustomSelect, SelectProvider } from '@rentnerkev/select'
export default function SharedDefaults() {
const [value, setValue] = useState('')
return (
<SelectProvider locale="en" searchable={false}>
<CustomSelect
label="Package"
onValueChange={setValue}
options={[{ value: 'toasts', label: 'Toasts' }]}
value={value}
/>
</SelectProvider>
)
}isSingleValueEmpty()#
El helper /value considera vacíos una cadena vacía, null y undefined para una selección única. Devuelve un booleano y acota el tipo de TypeScript.
import { isSingleValueEmpty } from '@rentnerkev/select/value'
export const hasSelection = !isSingleValueEmpty('tooltips')
export const isEmpty = isSingleValueEmpty(null)toggleSelectedValue()#
Alterna un valor en un array de selección de solo lectura usando tu función de igualdad. Los valores existentes se eliminan; los nuevos se añaden al final. Devuelve null si añadir el valor superaría maxSelection. No modifica el array original.
import { toggleSelectedValue } from '@rentnerkev/select/value'
export const next = toggleSelectedValue(
['tooltips'],
'toasts',
(option, value) => option === value,
2,
)Traducciones y resolveSelectMessages()#
selectMessageCatalog incluye en, de, es y fr. resolveSelectMessages combina tus cambios con ese idioma. Los mensajes cubren las selecciones obligatorias, mínimas y máximas, la búsqueda, los estados vacíos y el borrado. Los mensajes minSelection y maxSelection son funciones que reciben la cantidad.
import { resolveSelectMessages, selectMessageCatalog } from '@rentnerkev/select'
export const messages = resolveSelectMessages('en', {
noResults: 'No package found',
maxSelection: (count) => 'Choose up to ' + count + ' packages',
clearSelection: selectMessageCatalog.en.clearSelection,
})Espacios de clases y diseño personalizado#
className aplica estilos al componente exterior. classNames ofrece espacios root, trigger, content, search, viewport, option, empty, label, description y clear. Define solo los espacios que quieras cambiar y conserva los valores compartidos en SelectProvider. Importa la hoja de estilos de Tailwind una sola vez.
import { useState } from 'react'
import { CustomSelect } from '@rentnerkev/select'
import type { SelectClassNames } from '@rentnerkev/select/types'
const classNames: SelectClassNames = {
trigger: 'border-2 border-amber-700 bg-amber-50 text-stone-900',
content: 'bg-amber-50 text-stone-900',
label: 'font-bold',
}
export default function StyledSelect() {
const [value, setValue] = useState('')
return (
<CustomSelect
classNames={classNames}
label="Package"
onValueChange={setValue}
options={[{ value: 'calendar', label: 'Calendar' }]}
value={value}
/>
)
}Documentación para tus herramientas de IA
Conecta un cliente MCP compatible para leer las API, guías y ejemplos de los paquetes. Acceso público, sin cuenta ni clave de API.
El acceso remoto es opcional: añade tú mismo esta URL pública a tu cliente MCP. La conexión usa Streamable HTTP; el formato de configuración puede variar. Las herramientas /ai locales leen la versión instalada en Node.js o Bun y nunca se conectan automáticamente a este servidor.
{
"mcpServers": {
"rentnerPackages": {
"url": "https://packages.rentner.dev/mcp"
}
}
}Herramientas: list_packages, read_package_docs, read_package_api, read_package_examples y search_package_docs.
TypeScript / v6.2.0
API y tipos
Firmas, props y tipos publicados para esta versión. Abre una entrada para consultar su definición y las rutas de importación disponibles.
CustomSelectfunction
@rentnerkev/select@rentnerkev/select/select
export function CustomSelect<TValue = string>(props: LegacySingleSelectProps<TValue>): ReactElement
export function CustomSelect<TValue = string>(props: DirectClearableSingleSelectProps<TValue>): ReactElement
export function CustomSelect<TValue = string>(props: ConfiguredClearableSingleSelectProps<TValue>): ReactElement
export function CustomSelect<TValue = string>(props: DefaultSingleSelectProps<TValue>): ReactElement
export function CustomSelect<TValue = string>(props: MultipleSelectProps<TValue>): ReactElement
export function CustomSelect<TValue = string>(props: CustomSelectProps<TValue>): ReactElement
export function CustomSelect(props: CustomSelectProps<string>): ReactElementSelectProviderfunction
@rentnerkev/select
export function SelectProvider({ children, ...props }: SelectProviderProps): import("react").JSX.ElementresolveSelectMessagesfunction
@rentnerkev/select@rentnerkev/select/messages
export function resolveSelectMessages(locale?: SelectLocale, messages?: Partial<SelectMessages>): SelectMessagesselectMessageCatalogconst
@rentnerkev/select@rentnerkev/select/messages
export const selectMessageCatalog: Record<SelectLocale, SelectMessages>CustomSelectPropstype
@rentnerkev/select@rentnerkev/select/types
export type CustomSelectProps<TValue = string> = SingleSelectProps<TValue> | MultipleSelectProps<TValue>MultipleSelectPropstype
@rentnerkev/select@rentnerkev/select/types
export type MultipleSelectProps<TValue = string> = SharedCustomSelectProps<TValue> & ClearableSelectProps & {
value: ReadonlyArray<TValue>
onValueChange: (value: Array<TValue>) => void
multiple: true
/** Enable removal from the built-in closed selection labels. Defaults to false renderValue takes precedence. */
removableSelectedItems?: boolean
emptyValue?: never
omitEmptyFormValue?: boolean
minSelection?: number
maxSelection?: number
}
interface SharedCustomSelectProps<TValue> extends AriaAttributes, SelectCustomizationProps {
id?: string
name?: string
options: ReadonlyArray<Option<TValue>>
required?: boolean
label?: ReactNode
description?: ReactNode
error?: string | null
disabled?: boolean
readOnly?: boolean
triggerRef?: Ref<HTMLButtonElement>
onBlur?: FocusEventHandler<HTMLDivElement>
icon?: ReactNode
placeholder?: string
className?: string
classNames?: SelectClassNames
searchable?: boolean
nonce?: string
renderOption?: (option: Option<TValue>, state: SelectOptionState) => ReactNode
renderValue?: (options: ReadonlyArray<Option<TValue>>) => ReactNode
fallbackOption?: string
locale?: SelectLocale
messages?: Partial<SelectMessages>
isOptionEqualToValue?: (optionValue: TValue, value: TValue) => boolean
getFormValue?: (value: TValue) => string
}
type ClearableSelectProps = {
clearable: true
onClear?: () => void
} | {
clearable?: false
onClear?: never
}SelectClassNamesinterface
@rentnerkev/select@rentnerkev/select/types
export interface SelectClassNames {
root?: string
trigger?: string
content?: string
search?: string
viewport?: string
option?: string
group?: string
groupLabel?: string
createOption?: string
empty?: string
label?: string
description?: string
clear?: string
control?: string
error?: string
leading?: string
trailing?: string
optionLabel?: string
optionDescription?: string
optionIndicator?: string
selectedLabel?: string
selectedDescription?: string
selectedItems?: string
selectedItem?: string
}SelectOptionStateinterface
@rentnerkev/select@rentnerkev/select/types
export interface SelectOptionState {
selected: boolean
disabled: boolean
}SingleSelectPropstype
@rentnerkev/select@rentnerkev/select/types
export type SingleSelectProps<TValue = string> = LegacySingleSelectProps<TValue> | DirectClearableSingleSelectProps<TValue> | ConfiguredClearableSingleSelectProps<TValue> | DefaultSingleSelectProps<TValue>SelectProviderPropsinterface
@rentnerkev/select@rentnerkev/select/types
export interface SelectProviderProps extends SelectCustomizationProps {
children: ReactNode
locale?: SelectLocale
messages?: Partial<SelectMessages>
classNames?: SelectClassNames
searchable?: boolean
nonce?: string
}SelectVirtualizationOptionsinterface
@rentnerkev/select@rentnerkev/select/types
export interface SelectVirtualizationOptions {
estimateSize?: number
overscan?: number
}Optioninterface
@rentnerkev/select@rentnerkev/select/types
export interface Option<TValue = string> {
value: TValue
label: string
subOption?: string
group?: string
disabled?: boolean
}SelectLocaletype
@rentnerkev/select@rentnerkev/select/messages@rentnerkev/select/types
export type SelectLocale = 'de' | 'en' | 'es' | 'fr'SelectMessagesinterface
@rentnerkev/select@rentnerkev/select/messages@rentnerkev/select/types
export interface SelectMessages {
loading?: string
createOption?: (value: string) => string
clickToRemove?: string
removeSelectedItem?: (label: string) => string
required: string
minSelection: (count: number) => string
maxSelection: (count: number) => string
searchOptions: string
searchPlaceholder: string
noResults: string
noOptions: string
clearSelection: string
}Comboboxfunction
@rentnerkev/select@rentnerkev/select/combobox
export function Combobox<T>(props: SingleComboboxProps<T>): ReactElement
export function Combobox<T>(props: MultipleComboboxProps<T>): ReactElement
export function Combobox<T>(props: ComboboxProps<T>): ReactElementComboboxPropstype
@rentnerkev/select@rentnerkev/select/combobox@rentnerkev/select/combobox/types
export type ComboboxProps<T> = SingleComboboxProps<T> | MultipleComboboxProps<T>getSelectFieldPropsfunction
@rentnerkev/select@rentnerkev/select/form
export function getSelectFieldProps<T>(field: SelectFormField<T>, options?: SelectFormOptions): SelectFieldProps<T>getReadableSelectErrorfunction
@rentnerkev/select@rentnerkev/select/form
export function getReadableSelectError(error: unknown): string | undefinedSelectFormFieldinterface
@rentnerkev/select@rentnerkev/select/form
export interface SelectFormField<T> {
name: string
state: {
value: T
meta?: {
errors?: ReadonlyArray<unknown>
isTouched?: boolean
}
}
handleChange: (value: T) => void
handleBlur: () => void
}SelectFormOptionsinterface
@rentnerkev/select@rentnerkev/select/form
export interface SelectFormOptions {
errorVisibility?: 'touched' | 'always' | 'never'
mapError?: (error: unknown) => string | undefined
}SelectFieldPropsinterface
@rentnerkev/select@rentnerkev/select/form
export interface SelectFieldProps<T> {
name: string
value: T
onValueChange: (value: T) => void
onBlur: () => void
error: string | null
}SelectCustomizationPropsinterface
@rentnerkev/select@rentnerkev/select/types
export interface SelectCustomizationProps {
/** Auto by default: CustomSelect >= 250 options, Combobox >= 1000 true/options force on, false forces off. */
virtualized?: boolean | 'auto' | SelectVirtualizationOptions
controlSize?: 'sm' | 'md' | 'lg'
textOverflow?: 'truncate' | 'wrap'
contentWidth?: 'trigger' | 'content'
portalContainer?: Element | DocumentFragment | null
portalClassName?: string
portalZIndex?: number
}isSingleValueEmptyfunction
@rentnerkev/select/value
export function isSingleValueEmpty(value: unknown): value is '' | null | undefinedtoggleSelectedValuefunction
@rentnerkev/select/value
export function toggleSelectedValue<TValue>(selectedValues: ReadonlyArray<TValue>, nextValue: TValue, isEqual: SelectValueComparator<TValue>, maxSelection?: number): Array<TValue> | nullSelectValueComparatortype
@rentnerkev/select/value
export type SelectValueComparator<TValue> = (optionValue: TValue, value: TValue) => booleanLegacySingleSelectPropstype
@rentnerkev/select/types
export type LegacySingleSelectProps<TValue = string> = SingleSelectPropsBase<TValue> & {
clearable: true
onClear: () => void
emptyValue?: never
onValueChange: (value: TValue) => void
}
type SingleSelectPropsBase<TValue> = SharedCustomSelectProps<TValue> & {
value: TValue | null | undefined
multiple?: false
removableSelectedItems?: never
}
interface SharedCustomSelectProps<TValue> extends AriaAttributes, SelectCustomizationProps {
id?: string
name?: string
options: ReadonlyArray<Option<TValue>>
required?: boolean
label?: ReactNode
description?: ReactNode
error?: string | null
disabled?: boolean
readOnly?: boolean
triggerRef?: Ref<HTMLButtonElement>
onBlur?: FocusEventHandler<HTMLDivElement>
icon?: ReactNode
placeholder?: string
className?: string
classNames?: SelectClassNames
searchable?: boolean
nonce?: string
renderOption?: (option: Option<TValue>, state: SelectOptionState) => ReactNode
renderValue?: (options: ReadonlyArray<Option<TValue>>) => ReactNode
fallbackOption?: string
locale?: SelectLocale
messages?: Partial<SelectMessages>
isOptionEqualToValue?: (optionValue: TValue, value: TValue) => boolean
getFormValue?: (value: TValue) => string
}DirectClearableSingleSelectPropstype
@rentnerkev/select/types
export type DirectClearableSingleSelectProps<TValue = string> = SingleSelectPropsBase<TValue> & {
clearable: true
onClear?: never
emptyValue?: null
onValueChange: (value: TValue | null) => void
}
type SingleSelectPropsBase<TValue> = SharedCustomSelectProps<TValue> & {
value: TValue | null | undefined
multiple?: false
removableSelectedItems?: never
}
interface SharedCustomSelectProps<TValue> extends AriaAttributes, SelectCustomizationProps {
id?: string
name?: string
options: ReadonlyArray<Option<TValue>>
required?: boolean
label?: ReactNode
description?: ReactNode
error?: string | null
disabled?: boolean
readOnly?: boolean
triggerRef?: Ref<HTMLButtonElement>
onBlur?: FocusEventHandler<HTMLDivElement>
icon?: ReactNode
placeholder?: string
className?: string
classNames?: SelectClassNames
searchable?: boolean
nonce?: string
renderOption?: (option: Option<TValue>, state: SelectOptionState) => ReactNode
renderValue?: (options: ReadonlyArray<Option<TValue>>) => ReactNode
fallbackOption?: string
locale?: SelectLocale
messages?: Partial<SelectMessages>
isOptionEqualToValue?: (optionValue: TValue, value: TValue) => boolean
getFormValue?: (value: TValue) => string
}ConfiguredClearableSingleSelectPropstype
@rentnerkev/select/types
export type ConfiguredClearableSingleSelectProps<TValue = string> = SingleSelectPropsBase<TValue> & {
clearable: true
onClear?: never
emptyValue: TValue
onValueChange: (value: TValue) => void
}
type SingleSelectPropsBase<TValue> = SharedCustomSelectProps<TValue> & {
value: TValue | null | undefined
multiple?: false
removableSelectedItems?: never
}
interface SharedCustomSelectProps<TValue> extends AriaAttributes, SelectCustomizationProps {
id?: string
name?: string
options: ReadonlyArray<Option<TValue>>
required?: boolean
label?: ReactNode
description?: ReactNode
error?: string | null
disabled?: boolean
readOnly?: boolean
triggerRef?: Ref<HTMLButtonElement>
onBlur?: FocusEventHandler<HTMLDivElement>
icon?: ReactNode
placeholder?: string
className?: string
classNames?: SelectClassNames
searchable?: boolean
nonce?: string
renderOption?: (option: Option<TValue>, state: SelectOptionState) => ReactNode
renderValue?: (options: ReadonlyArray<Option<TValue>>) => ReactNode
fallbackOption?: string
locale?: SelectLocale
messages?: Partial<SelectMessages>
isOptionEqualToValue?: (optionValue: TValue, value: TValue) => boolean
getFormValue?: (value: TValue) => string
}DefaultSingleSelectPropstype
@rentnerkev/select/types
export type DefaultSingleSelectProps<TValue = string> = SingleSelectPropsBase<TValue> & {
clearable?: false
onClear?: never
emptyValue?: never
onValueChange: (value: TValue) => void
}
type SingleSelectPropsBase<TValue> = SharedCustomSelectProps<TValue> & {
value: TValue | null | undefined
multiple?: false
removableSelectedItems?: never
}
interface SharedCustomSelectProps<TValue> extends AriaAttributes, SelectCustomizationProps {
id?: string
name?: string
options: ReadonlyArray<Option<TValue>>
required?: boolean
label?: ReactNode
description?: ReactNode
error?: string | null
disabled?: boolean
readOnly?: boolean
triggerRef?: Ref<HTMLButtonElement>
onBlur?: FocusEventHandler<HTMLDivElement>
icon?: ReactNode
placeholder?: string
className?: string
classNames?: SelectClassNames
searchable?: boolean
nonce?: string
renderOption?: (option: Option<TValue>, state: SelectOptionState) => ReactNode
renderValue?: (options: ReadonlyArray<Option<TValue>>) => ReactNode
fallbackOption?: string
locale?: SelectLocale
messages?: Partial<SelectMessages>
isOptionEqualToValue?: (optionValue: TValue, value: TValue) => boolean
getFormValue?: (value: TValue) => string
}SelectDefaultstype
@rentnerkev/select/types
export type SelectDefaults = Omit<SelectProviderProps, 'children'>SelectOptionHandlersinterface
@rentnerkev/select/types
export interface SelectOptionHandlers<TValue> {
handleOptionPointerDown: (event?: PointerEvent<HTMLDivElement>) => void
handleOptionPointerUp?: (event: PointerEvent<HTMLDivElement>, value: string) => void
handleOptionPointerMove?: (event: PointerEvent<HTMLDivElement>) => void
handleOptionClick?: (event: MouseEvent<HTMLDivElement>, value: string) => void
handleOptionFocus: (value: TValue, event?: FocusEvent<HTMLDivElement>) => void
handleOptionBlur: (event: FocusEvent<HTMLDivElement>) => void
handleOptionKeyDown: (event: KeyboardEvent<HTMLDivElement>) => void
}SelectOptionsPropsinterface
@rentnerkev/select/types
export interface SelectOptionsProps<TValue> {
entries: ReadonlyArray<OptionEntry<TValue>>
multiple: boolean
renderOption: SharedCustomSelectProps<TValue>['renderOption']
className: string | undefined
classNames: SelectClassNames
textOverflow: 'truncate' | 'wrap'
isSelected: (value: TValue) => boolean
isOptionDisabled: (option: Option<TValue>) => boolean
handler: SelectOptionHandlers<TValue>
}
interface SharedCustomSelectProps<TValue> extends AriaAttributes, SelectCustomizationProps {
id?: string
name?: string
options: ReadonlyArray<Option<TValue>>
required?: boolean
label?: ReactNode
description?: ReactNode
error?: string | null
disabled?: boolean
readOnly?: boolean
triggerRef?: Ref<HTMLButtonElement>
onBlur?: FocusEventHandler<HTMLDivElement>
icon?: ReactNode
placeholder?: string
className?: string
classNames?: SelectClassNames
searchable?: boolean
nonce?: string
renderOption?: (option: Option<TValue>, state: SelectOptionState) => ReactNode
renderValue?: (options: ReadonlyArray<Option<TValue>>) => ReactNode
fallbackOption?: string
locale?: SelectLocale
messages?: Partial<SelectMessages>
isOptionEqualToValue?: (optionValue: TValue, value: TValue) => boolean
getFormValue?: (value: TValue) => string
}CustomSelectLogicResultinterface
@rentnerkev/select/types
export interface CustomSelectLogicResult<TValue> {
state: SelectCustomizationProps & {
popupStyle: CSSProperties
popupId: string
portalTarget: Element | DocumentFragment | null
virtualOptionsModule: typeof import('../Components/VirtualSelectOptions.tsx') | null
virtualized: boolean | SelectVirtualizationOptions
textOverflow: 'truncate' | 'wrap'
contentWidth: 'trigger' | 'content'
name: string | undefined
required: boolean
disabled: boolean
readOnly: boolean
externalError: string | null | undefined
label: ReactNode
description: ReactNode
icon: ReactNode
placeholder: string | undefined
className: string | undefined
classNames: SelectClassNames
searchable: boolean
nonce: string | undefined
renderOption: SharedCustomSelectProps<TValue>['renderOption']
renderValue: SharedCustomSelectProps<TValue>['renderValue']
fallbackOption: string | undefined
multiple: boolean
omitEmptyFormValue: boolean
clearable: boolean
selectedValues: ReadonlyArray<TValue>
formEntries: ReadonlyArray<{
key: string
value: string
}>
ariaProps: AriaAttributes
ariaLabel: string | undefined
describedBy: string | undefined
labelledBy: string | undefined
showClear: boolean
showRemovableSelectedItems?: boolean
isOptionDisabled: (option: Option<TValue>) => boolean
selectedOptions: ReadonlyArray<Option<TValue>>
selectedLabel: string
messages: SelectMessages
triggerId: string
labelId: string
descriptionId: string
errorId: string
open: boolean
searchValue: string
optionEntries: ReadonlyArray<OptionEntry<TValue>>
filteredOptions: ReadonlyArray<OptionEntry<TValue>>
selectedEntries: ReadonlyArray<OptionEntry<TValue>>
selectedRadixValue: string
hasError: boolean
resolvedError: string | null
hasLeftIcon: boolean
isOptionEqualToValue: (optionValue: TValue, value: TValue) => boolean
isValueSelected: (value: TValue) => boolean
}
handler: {
option: SelectOptionHandlers<TValue>
handleVirtualClose: () => void
handleContentFocusCapture: (event: FocusEvent<HTMLDivElement>) => void
handleTriggerPointerDown: (event: PointerEvent<HTMLButtonElement>) => void
handleTriggerClick: () => void
handleTriggerKeyDown: (event: KeyboardEvent<HTMLButtonElement>) => void
handleSearchChange: (event: ChangeEvent<HTMLInputElement>) => void
handleSearchPointerDown: (event: PointerEvent<HTMLInputElement>) => void
handleSearchKeyDown: (event: KeyboardEvent<HTMLInputElement>) => void
handleFieldBlur: (event: FocusEvent<HTMLDivElement>) => void
handleInvalid: (event: InvalidEvent<HTMLInputElement>) => void
handleValueChange: (value: string) => void
handleClear: () => void
handleRemoveSelectedItem?: (optionKey: string) => void
handleOpenChange: (open: boolean) => void
closeAfterOptionRemoval: () => void
handleContentKeyDownCapture: (event: KeyboardEvent<HTMLDivElement>) => void
}
refs: {
root: RefObject<HTMLDivElement | null>
content: RefObject<HTMLDivElement | null>
overlayContent: RefCallback<HTMLDivElement>
trigger: RefCallback<HTMLButtonElement>
searchInput: RefObject<HTMLInputElement | null>
validationInput: RefObject<HTMLInputElement | null>
scroll: RefObject<HTMLDivElement | null>
virtualNavigation: RefObject<SelectVirtualNavigation | null>
pendingVirtualNavigation: RefObject<Array<KeyboardEvent<HTMLDivElement>>>
}
}
interface SharedCustomSelectProps<TValue> extends AriaAttributes, SelectCustomizationProps {
id?: string
name?: string
options: ReadonlyArray<Option<TValue>>
required?: boolean
label?: ReactNode
description?: ReactNode
error?: string | null
disabled?: boolean
readOnly?: boolean
triggerRef?: Ref<HTMLButtonElement>
onBlur?: FocusEventHandler<HTMLDivElement>
icon?: ReactNode
placeholder?: string
className?: string
classNames?: SelectClassNames
searchable?: boolean
nonce?: string
renderOption?: (option: Option<TValue>, state: SelectOptionState) => ReactNode
renderValue?: (options: ReadonlyArray<Option<TValue>>) => ReactNode
fallbackOption?: string
locale?: SelectLocale
messages?: Partial<SelectMessages>
isOptionEqualToValue?: (optionValue: TValue, value: TValue) => boolean
getFormValue?: (value: TValue) => string
}InternalCustomSelectLogicResulttype
@rentnerkev/select/types
export type InternalCustomSelectLogicResult<TValue> = CustomSelectLogicResult<TValue> & {
handler: {
handleRemoveSelectedItem: (optionKey: string) => void
}
}SelectProviderLogicResultinterface
@rentnerkev/select/types
export interface SelectProviderLogicResult {
state: {
contextValue: SelectDefaults
}
}SelectValueOptionstype
@rentnerkev/select/types
export type SelectValueOptions<TValue> = Pick<SingleSelectProps<TValue>, SelectValueKeys> | Pick<MultipleSelectProps<TValue>, SelectValueKeys | 'maxSelection'>
type SelectValueKeys = 'value' | 'onValueChange' | 'multiple' | 'options' | 'emptyValue' | 'onClear' | 'getFormValue' | 'isOptionEqualToValue'SelectValuesResultinterface
@rentnerkev/select/types
export interface SelectValuesResult<TValue> {
state: {
selectedValues: ReadonlyArray<TValue>
formEntries: ReadonlyArray<{
key: string
value: string
}>
}
handler: {
handleSelectValue: (value: TValue) => void
handleClearValues: () => void
}
}SelectOptionIdentityResultinterface
@rentnerkev/select/types
export interface SelectOptionIdentityResult<TValue> {
state: {
optionEntries: ReadonlyArray<OptionEntry<TValue>>
}
}PackageInfointerface
@rentnerkev/select/ai
export interface PackageInfo {
name: string
version: string
description: string
license: string
homepage: string
repository: {
type: string
url: string
}
exports: Record<string, string | {
types?: string
import?: string
default?: string
}>
peerDependencies: Record<string, string>
}PackageDocumentinterface
@rentnerkev/select/ai
export interface PackageDocument {
path: string
content: string
}PackageApiinterface
@rentnerkev/select/ai
export interface PackageApi {
package: string
version: string
subpaths: Record<string, string>
declarations: PackageDocument[]
}PackageSearchMatchinterface
@rentnerkev/select/ai
export interface PackageSearchMatch {
path: string
line: number
text: string
}PackageExampleinterface
@rentnerkev/select/ai
export interface PackageExample {
language: string
code: string
}getPackageInfofunction
@rentnerkev/select/ai
export function getPackageInfo(): PackageInfogetPackageDocumentationfunction
@rentnerkev/select/ai
export function getPackageDocumentation(document?: 'readme' | 'usage'): PackageDocumentgetPackageApifunction
@rentnerkev/select/ai
export function getPackageApi(options?: {
subpath?: string
symbol?: string
}): PackageApisearchPackageDocumentationfunction
@rentnerkev/select/ai
export function searchPackageDocumentation(query: string): PackageSearchMatch[]getPackageExamplesfunction
@rentnerkev/select/ai
export function getPackageExamples(): PackageExample[]ComboboxBasePropsinterface
@rentnerkev/select/combobox/types
export interface ComboboxBaseProps<T> extends AriaAttributes, SelectCustomizationProps {
options: ReadonlyArray<T>
searchValue: string
onSearchValueChange: (value: string) => void
getOptionKey: (option: T) => string
getOptionLabel: (option: T) => string
getOptionGroup?: (option: T) => string | undefined
/** Receives a trimmed query the application owns creating and selecting the new option. */
onCreateOption?: (searchValue: string) => void
createOptionLabel?: (searchValue: string) => string
getOptionDescription?: (option: T) => ReactNode
isOptionDisabled?: (option: T) => boolean
isOptionEqualToValue?: (option: T, value: T) => boolean
renderOption?: (option: T, state: {
selected: boolean
active: boolean
disabled: boolean
}) => ReactNode
filterMode?: 'external' | 'local'
loading?: boolean
loadingText?: ReactNode
emptyText?: ReactNode
clearable?: boolean
id?: string
name?: string
getFormValue?: (value: T) => string
label?: ReactNode
description?: ReactNode
error?: string | null
required?: boolean
disabled?: boolean
readOnly?: boolean
placeholder?: string
inputRef?: Ref<HTMLInputElement>
onBlur?: (event: FocusEvent<HTMLDivElement>) => void
className?: string
classNames?: SelectClassNames
locale?: SelectLocale
messages?: Partial<SelectMessages>
}SingleComboboxPropsinterface
@rentnerkev/select/combobox/types
export interface SingleComboboxProps<T> extends ComboboxBaseProps<T> {
multiple?: false
value: T | null
onValueChange: (value: T | null) => void
}MultipleComboboxPropsinterface
@rentnerkev/select/combobox/types
export interface MultipleComboboxProps<T> extends ComboboxBaseProps<T> {
multiple: true
value: ReadonlyArray<T>
onValueChange: (value: T[]) => void
}ComboboxEntryinterface
@rentnerkev/select/combobox/types
export interface ComboboxEntry<T> {
option: T
key: string
id: string
label: string
group?: string
position?: number
description: ReactNode
disabled: boolean
selected: boolean
}ComboboxLogicResultinterface
@rentnerkev/select/combobox/types
export interface ComboboxLogicResult<T> {
state: {
virtualOptionsModule: typeof import('../Components/VirtualComboboxOptions.tsx') | null
inputId: string
listId: string
hasLabel: boolean
labelId: string
descriptionId: string
errorId: string
labelledBy: string | undefined
describedBy: string | undefined
open: boolean
activeId: string | undefined
activeEntry: ComboboxEntry<T> | undefined
activeIndex: number
navigationVersion: number
virtualization: boolean | SelectVirtualizationOptions
entries: ReadonlyArray<ComboboxEntry<T>>
messages: SelectMessages
classNames: SelectClassNames
controlSize: SelectCustomizationProps['controlSize']
textOverflow: 'truncate' | 'wrap'
portalContainer: Element | DocumentFragment | null | undefined
portalClassName: string | undefined
popupStyle: CSSProperties
multiple: boolean
selectedItems: ReadonlyArray<{
key: string
label: string
disabled: boolean
removeLabel: string
}>
formValues: ReadonlyArray<{
key: string
value: string
}>
emptySelection: boolean
formValue: string
hasError: boolean
error: string | null | undefined
loadingText: ReactNode
emptyText: ReactNode
showClear: boolean
canCreate?: boolean
createLabel?: string
createId?: string
createActive?: boolean
}
handler: {
handleChange: (event: ChangeEvent<HTMLInputElement>) => void
handleFocus: () => void
handleKeyDown: (event: KeyboardEvent<HTMLInputElement>) => void
handleFieldBlur: (event: FocusEvent<HTMLDivElement>) => void
handleOptionSelect: (entry: ComboboxEntry<T>) => void
handleOptionActivate: (key: string) => void
handleKeepFocus: (event: MouseEvent<HTMLElement>) => void
handleClear: () => void
handleRemoveSelectedItem: (key: string) => void
handleInvalid: (event: InvalidEvent<HTMLInputElement>) => void
handleCreateOption?: () => void
handleCreateActivate?: () => void
}
refs: {
root: RefObject<HTMLDivElement | null>
content: RefObject<HTMLDivElement | null>
popupContent: RefCallback<HTMLDivElement>
validation: RefObject<HTMLInputElement | null>
input: RefCallback<HTMLInputElement>
}
}InternalComboboxLogicResulttype
@rentnerkev/select/combobox/types
export type InternalComboboxLogicResult<T> = ComboboxLogicResult<T> & {
state: {
entries: ReadonlyArray<ComboboxEntry<T> & {
position: number
}>
}
}ComboboxOptionPropsinterface
@rentnerkev/select/combobox/types
export interface ComboboxOptionProps<T> {
entry: ComboboxEntry<T>
state: Pick<ComboboxLogicResult<T>['state'], 'activeId' | 'classNames' | 'textOverflow'>
handler: Pick<ComboboxLogicResult<T>['handler'], 'handleKeepFocus' | 'handleOptionActivate' | 'handleOptionSelect'>
renderOption: ComboboxProps<T>['renderOption']
index?: number
setSize?: number
measureElement?: RefCallback<HTMLDivElement>
style?: CSSProperties
}VirtualComboboxOptionsPropsinterface
@rentnerkev/select/combobox/types
export interface VirtualComboboxOptionsProps<T> {
state: Pick<ComboboxLogicResult<T>['state'], 'multiple' | 'listId' | 'labelledBy' | 'entries' | 'activeId' | 'activeIndex' | 'navigationVersion' | 'virtualization' | 'classNames' | 'textOverflow' | 'popupStyle' | 'canCreate' | 'createId' | 'createLabel' | 'createActive'>
handler: ComboboxOptionProps<T>['handler'] & Pick<ComboboxLogicResult<T>['handler'], 'handleCreateOption' | 'handleCreateActivate'>
renderOption: ComboboxProps<T>['renderOption']
loading?: boolean
ariaLabel: string
}ComboboxCreateOptionPropsinterface
@rentnerkev/select/combobox/types
export interface ComboboxCreateOptionProps {
state: Pick<ComboboxLogicResult<unknown>['state'], 'createId' | 'createLabel' | 'createActive' | 'classNames' | 'entries'>
handler: Pick<ComboboxLogicResult<unknown>['handler'], 'handleCreateOption' | 'handleCreateActivate' | 'handleKeepFocus'>
}VirtualComboboxOptionsLogicResultinterface
@rentnerkev/select/combobox/types
export interface VirtualComboboxOptionsLogicResult<T> {
state: {
rows: ReadonlyArray<{
item: VirtualItem
entry: ComboboxEntry<T>
}>
totalSize: number
height: number
}
refs: {
viewport: RefObject<HTMLDivElement | null>
}
virtualizer: ReactVirtualizer<HTMLElement, HTMLElement>
}