Hoppa till huvudinnehåll

ComboBox

Flerval med sök, väljare med sök, dropdown med sök

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>
)
Välj det land du är medborgare i
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>
)
Länderna är grupperade efter världsdel

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ök på namn eller landskod

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>
)
Sök på namn eller typ av produkt, t.ex. laptop

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>
)
}
Skapa en ny om den inte finns i listan

API​

ComboBox​

NameTypeDefaultDescription
label-
description-
errorMessage-
itemsIterable<T>-

The options in the list. They are filtered by the search text, use defaultFilter={() => true} if they are already filtered elsewhere, for example on a server.

In the next major version, items will no longer be filtered, as in React Aria. Use defaultItems for a static list that should be filtered

placeholder-
errorPositiontop

The position of the error message

sizelarge

Component size (large: height 48px, medium: height 40px)

popover-
listBoxProps-
isDisabled-

Whether the input is disabled.

className'react-aria-ComboBox'

The CSS className for the element. A function may be provided to compute the class based on component state.

slot-

A slot name for the component. Slots allow the component to receive props from a parent component. An explicit null value indicates that the local props completely override all props received from a parent.

style-

The inline style for the element. A function may be provided to compute the style based on component state.

renderDOMRenderFunction<"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:

  • You must render the expected element type (e.g. if <button> is expected, you cannot render an <a>).
  • Only a single root DOM element can be rendered (no fragments).
  • You must pass through props and ref to the underlying DOM element, merging with your own prop as appropriate.
defaultValue-

The default value (uncontrolled).

autoFocus-

Whether the element should receive focus on render.

disabledKeysIterable<Key>-

The item keys that are disabled. These items cannot be selected, focused, or otherwise interacted with.

value-

The current value (controlled).

selectionMode'single'

Whether single or multiple selection is enabled.

isReadOnly-

Whether the input can be selected but not changed by the user.

isInvalid-

Whether the input value is invalid.

validationBehavior'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-

The currently selected key in the collection (controlled). @deprecated

defaultSelectedKey-

The initial selected key in the collection (uncontrolled). @deprecated

allowsEmptyCollection-

Whether the combo box allows the menu to be open when the collection is empty.

isRequired-

Whether user input is required on the input before form submission.

validate-

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 validationBehavior="native". For realtime validation, use the isInvalid prop instead.

shouldFocusWrap-

Whether keyboard navigation is circular.

defaultItemsIterable<T>-

The list of ComboBox items (uncontrolled).

inputValue-

The value of the ComboBox input (controlled).

defaultInputValue-

The default value of the ComboBox input (uncontrolled).

allowsCustomValue-

Whether the ComboBox allows a non-item matching input value to be set.

menuTrigger'input'

The interaction required to display the ComboBox menu.

defaultFilter-

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 useFilter is used.

formValue'key'

Whether the text or key of the selected item is submitted as part of an HTML form. When allowsCustomValue is true, this option does not apply and the text is always submitted.

ListBoxItem​