ComboBox
En ComboBox är en sökbar version av Select. Combobox är lämplig att använda när listan med möjliga val är lång eftersom det ger användaren möjlighet att söka efter ett specifikt värde.
import { ComboBox, ListBoxItem } from '@midas-ds/components'
<ComboBox label='Land'>
<ListBoxItem id='SE'>Sverige</ListBoxItem>
<ListBoxItem id='NO'>Norge</ListBoxItem>
<ListBoxItem id='DK'>Danmark</ListBoxItem>
<ListBoxItem id='FI'>Finland</ListBoxItem>
<ListBoxItem id='IS'>Island</ListBoxItem>
</ComboBox>
Kontrollerat val
Använd value och onChange för att styra det valda värdet i ComboBox.
import React from 'react'
import { Key } from '@midas-ds/components'
const [selectedCountry, setSelectedCountry] = React.useState<Key | null>(null)
return (
<ComboBox
label='Medborgarskap'
description='Välj det land du är medborgare i'
value={selectedCountry}
onChange={setSelectedCountry}
>
<ListBoxItem id='SE'>Sverige</ListBoxItem>
<ListBoxItem id='NO'>Norge</ListBoxItem>
<ListBoxItem id='DK'>Danmark</ListBoxItem>
<ListBoxItem id='FI'>Finland</ListBoxItem>
<ListBoxItem id='IS'>Island</ListBoxItem>
{/* … */}
</ComboBox>
)
Valt land:
Flerval
För närvarande stödjer inte vår ComboBox flerval. Använd Midas CSS för react-select för detta.
Sektioner
Vid många val kan alternativen struktureras i sektioner genom att dela in dem enligt följande:
import { Collection, ListBoxHeader, ListBoxItem, ListBoxSection } from '@midas-ds/components'
const options = [
{
name: 'Europa',
children: [
{ name: 'Frankrike', id: 'FR' },
{ name: 'Polen', id: 'PL' },
{ name: 'Sverige', id: 'SE' },
{ name: 'Tyskland', id: 'DE' },
{ name: 'Ukraina', id: 'UA' },
],
},
{
name: 'Asien',
children: [
{ name: 'Indien', id: 'IN' },
{ name: 'Japan', id: 'JP' },
{ name: 'Kina', id: 'CN' },
{ name: 'Vietnam', id: 'VN' },
],
},
{
name: 'Afrika',
children: [
{ name: 'Egypten', id: 'EG' },
{ name: 'Kenya', id: 'KE' },
{ name: 'Marocko', id: 'MA' },
{ name: 'Nigeria', id: 'NG' },
],
},
]
return (
<ComboBox
label='Land'
description='Länderna är grupperade efter världsdel'
defaultItems={options}
>
{section => (
<ListBoxSection id={section.name}>
<ListBoxHeader>{section.name}</ListBoxHeader>
<Collection items={section.children}>
{item => {
return <ListBoxItem id={item.id}>{item.name}</ListBoxItem>
}}
</Collection>
</ListBoxSection>
)}
</ComboBox>
)
Namn och kod
Texten i alternativet är också det som hamnar i fältet efter ett val, och det som sökningen matchar mot. Visa koden i texten, så kan användaren söka på både namn och kod.
const countries = [
{ id: 'SE', name: 'Sverige' },
{ id: 'NO', name: 'Norge' },
{ id: 'DK', name: 'Danmark' },
{ id: 'FI', name: 'Finland' },
// …
]
return (
<ComboBox
label='Land'
description='Sök på namn eller landskod'
defaultItems={countries}
>
{country => (
<ListBoxItem id={country.id}>{`${country.name} (${country.id})`}</ListBoxItem>
)}
</ComboBox>
)
Sökning på servern
När alternativen hämtas från en server sköter servern sökningen. Som standard filtrerar ComboBox ändå alternativen på söktexten, och då försvinner träffar där sökningen matchade något som inte syns i alternativet, till exempel en kod eller ett id. Stäng av filtreringen med defaultFilter={() => true}.
I exemplet söker API:et även i produktbeskrivningen. En sökning på "laptop" ger bland annat Lenovo Yoga 920, fast namnet inte innehåller söktexten.
import { useAsyncList } from 'react-stately'
import { Collection, ComboBox, ListBoxEmptyState, ListBoxItem, ListBoxLoadMoreItem } from '@midas-ds/components'
type Product = { id: number; title: string }
const list = useAsyncList<Product>({
async load({ signal, filterText = '' }) {
const res = await fetch(
`https://dummyjson.com/products/search?q=${encodeURIComponent(filterText)}&limit=10&select=title`,
{ signal },
)
const { products } = await res.json()
return { items: products }
},
})
return (
<ComboBox
label='Produkt'
description='Sök på namn eller typ av produkt, t.ex. laptop'
inputValue={list.filterText}
onInputChange={list.setFilterText}
defaultFilter={() => true}
allowsEmptyCollection
listBoxProps={{
renderEmptyState: () =>
list.isLoading ? null : <ListBoxEmptyState>Inga träffar</ListBoxEmptyState>,
}}
>
<Collection items={list.items}>
{product => <ListBoxItem id={product.id}>{product.title}</ListBoxItem>}
</Collection>
{list.isLoading && <ListBoxLoadMoreItem isLoading />}
</ComboBox>
)
allowsEmptyCollection gör att "Inga träffar" visas när sökningen inte ger något resultat, och ListBoxLoadMoreItem visar en laddningsindikator medan svaret hämtas. Fler exempel, bland annat med infinite scroll, finns i React Arias dokumentation för ComboBox.
Skapa alternativ
Använd onAction på <ListBoxItem> för att utföra valfria handlingar när användaren klickar eller trycker enter. Detta exempel visar hur användaren kan skapa ett nytt alternativ för angivet inputValue.
const ItemActionExample = () => {
const [items, setItems] = useState([
'Ekonomi',
'HR',
'IT',
'Juridik',
'Kommunikation',
])
const [inputValue, setInputValue] = useState('')
const selectedItem = items.includes(inputValue) ? inputValue : null
const selectItem = (key: Key | null) => {
if (key !== null) setInputValue(String(key))
}
const createItem = () => setItems(prev => [...prev, inputValue])
return (
<ComboBox
label='Kategori'
description='Skapa en ny om den inte finns i listan'
allowsEmptyCollection
inputValue={inputValue}
onInputChange={setInputValue}
value={selectedItem}
onChange={selectItem}
>
{inputValue.length > 0 && selectedItem === null && (
<ListBoxItem onAction={createItem}>
{`Skapa "${inputValue}"`}
</ListBoxItem>
)}
{items.map(item => (
<ListBoxItem
key={item}
id={item}
>
{item}
</ListBoxItem>
))}
</ComboBox>
)
}
API
ComboBox
| Name | Type | Default | Description |
|---|---|---|---|
label | string | - | |
description | string | - | |
errorMessage | ((validation: ValidationResult) => string) | string | - | |
items | Iterable<T> | - | The options in the list. They are filtered by the search text, use
In the next major version, |
placeholder | string | - | |
errorPosition | "bottom" | "top" | top | The position of the error message |
size | Size | large | Component size (large: height 48px, medium: height 40px) |
popover | InfoPopoverProps | - | |
listBoxProps | ListBoxProps<T> | - | |
isDisabled | boolean | - | Whether the input is disabled. |
className | ClassNameOrFunction<ComboBoxRenderProps> | 'react-aria-ComboBox' | The CSS className for the element. A function may be provided to compute the class based on component state. |
slot | string | null | - | A slot name for the component. Slots allow the component to receive props from a parent
component. An explicit |
style | StyleOrFunction<ComboBoxRenderProps> | - | The inline style for the element. A function may be provided to compute the style based on component state. |
render | DOMRenderFunction<"div", ComboBoxRenderProps> | - | Overrides the default DOM element with a custom render function. This allows rendering existing components with built-in styles and behaviors such as router links, animation libraries, and pre-styled components. Requirements:
|
defaultValue | Key | null | - | The default value (uncontrolled). |
autoFocus | boolean | - | Whether the element should receive focus on render. |
disabledKeys | Iterable<Key> | - | The item keys that are disabled. These items cannot be selected, focused, or otherwise interacted with. |
value | Key | null | - | The current value (controlled). |
selectionMode | "single" | 'single' | Whether single or multiple selection is enabled. |
isReadOnly | boolean | - | Whether the input can be selected but not changed by the user. |
isInvalid | boolean | - | Whether the input value is invalid. |
validationBehavior | "aria" | "native" | 'native' | Whether to use native HTML form validation to prevent form submission when the value is missing or invalid, or mark the field as required or invalid via ARIA. |
selectedKey | Key | null | - | The currently selected key in the collection (controlled). @deprecated |
defaultSelectedKey | Key | null | - | The initial selected key in the collection (uncontrolled). @deprecated |
allowsEmptyCollection | boolean | - | Whether the combo box allows the menu to be open when the collection is empty. |
isRequired | boolean | - | Whether user input is required on the input before form submission. |
validate | ((value: ComboBoxValidationValue<"single">) => true | ValidationError | null) | - | A function that returns an error message if a given value is invalid.
Validation errors are displayed to the user when the form is submitted
if |
shouldFocusWrap | boolean | - | Whether keyboard navigation is circular. |
defaultItems | Iterable<T> | - | The list of ComboBox items (uncontrolled). |
inputValue | string | - | The value of the ComboBox input (controlled). |
defaultInputValue | string | - | The default value of the ComboBox input (uncontrolled). |
allowsCustomValue | boolean | - | Whether the ComboBox allows a non-item matching input value to be set. |
menuTrigger | MenuTriggerAction | 'input' | The interaction required to display the ComboBox menu. |
defaultFilter | ((textValue: string, inputValue: string) => boolean) | - | The filter function used to determine if an option should be included in the combo box list.
By default, a language-sensitive "contains" filter from |
formValue | "key" | "text" | 'key' | Whether the text or key of the selected item is submitted as part of an HTML form. When
|