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='Välj din favoritfrukt'
description='Du kan bara välja en'
>
<ListBoxItem id='Lime'>Lime</ListBoxItem>
<ListBoxItem id='Äpple'>Äpple</ListBoxItem>
<ListBoxItem id='Banan'>Banan</ListBoxItem>
<ListBoxItem id='Kiwi'>Kiwi</ListBoxItem>
<ListBoxItem id='Apelsin'>Apelsin</ListBoxItem>
</ComboBox>
Du kan bara välja en

Kontrollerat val

Använd attributet id och eventet onSelectionChange för att använda controlled value på ComboBox. Den valda ListBoxItems värde skickas till callbacken, så kan du använda det för att uppdatera ditt state.

import React from 'react'
import { Key } from 'react-aria-components'

const [selectedFruit, setSelectedFruit] = React.useState<Key | null>(null)

return (
<ComboBox
label='Välj din favoritfrukt eller grönsak'
description='Du kan bara välja en'
selectedKey={selectedFruit}
onSelectionChange={setSelectedFruit}
>
<ListBoxItem id='Lime'>Lime</ListBoxItem>
<ListBoxItem id='Äpple'>Äpple</ListBoxItem>
<ListBoxItem id='Banan'>Banan</ListBoxItem>
<ListBoxItem id='Kiwi'>Kiwi</ListBoxItem>
<ListBoxItem id='Apelsin'>Apelsin</ListBoxItem>
</ComboBox>
)
Du kan bara välja en
Vald frukt: 

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 { ListBoxHeader, ListBoxItem, ListBoxSection } from '@midas-ds/components'
import { Collection } from 'react-aria-components'

const options = [
{
name: 'Grönsaker',
children: [
{ name: 'Morot', id: 2 },
{ name: 'Broccoli', id: 3 },
{ name: 'Spenat', id: 4 },
{ name: 'Potatis', id: 5 },
{ name: 'Tomat', id: 6 },
],
},
{
name: 'Frukter',
children: [
{ name: 'Äpple', id: 11 },
{ name: 'Banan', id: 12 },
{ name: 'Kiwi', id: 13 },
{ name: 'Fläder', id: 14 },
{ name: 'Nektarin', id: 15 },
],
},
]

return (
<ComboBox
label='Välj din favoritfrukt eller grönsak'
description='Du kan bara välja en'
items={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>
)
Du kan bara välja en

Asynkron laddning

Om data finns på en server kan en laddningsindikator visas med en ListBoxLoadMoreItem-komponent.

Använd allowsEmptyCollection hos ComboBox och rendera bara ListBoxLoadMoreItem vid laddning för att visa ett "inga-träffar"-meddelande om sökfrågan inte gav något resultat.

import { useAsyncList } from 'react-stately'
import { Collection } from 'react-aria-components'
import { ComboBox, ListBoxItem, ListBoxLoadMoreItem, ListBoxEmptyState } from '@midas-ds/components'

const list = useAsyncList<{ name: string }>({
async load({ signal, cursor, filterText }) {
if (cursor) {
cursor = cursor.replace(/^http:\/\//i, 'https://')
}

const res = await fetch(cursor || `https://swapi.py4e.com/api/people/?search=${filterText}`, { signal })

const { results, next } = await res.json()

return {
items: results,
cursor: next,
}
},
})

return (
<ComboBox
label='Star Wars Character Lookup'
placeholder='Välj eller sök karaktär'
description='Anropar ett externt API'
inputValue={list.filterText}
onInputChange={list.setFilterText}
allowsEmptyCollection
listBoxProps={{
renderEmptyState: () =>
list.isLoading ? null : (
<ListBoxEmptyState>Inga träffar</ListBoxEmptyState>
)
}}
>
<Collection items={list.items}>
{item => {
return <ListBoxItem id={item.name}>{item.name}</ListBoxItem>
}}
</Collection>
{list.isLoading && <ListBoxLoadMoreItem isLoading={list.isLoading} />}
</ComboBox>
)

Fler exempel med bland annat infinite scroll finns i React Arias dokumentation för ComboBox

Anropar ett externt API

API

ComboBox

NameTypeDefaultDescription
label-
description-
errorMessage-
items-

The list of ComboBox items (controlled).

placeholder-
errorPositiontop
sizelarge

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

popover-
listBoxProps-
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.

shouldFocusWrap-

Whether keyboard navigation is circular.

defaultItems-

The list of ComboBox items (uncontrolled).

selectionMode'single'

Whether single or multiple selection is enabled.

selectedKey-

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

defaultSelectedKey-

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

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.

disabledKeys-

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

isDisabled-

Whether the input is disabled.

isReadOnly-

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

value-

The current value (controlled).

defaultValue-

The default value (uncontrolled).

isRequired-

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

isInvalid-

Whether the input value is invalid.

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.

autoFocus-

Whether the element should receive focus on render.

className'react-aria-ComboBox'

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

defaultFilter-

The filter function used to determine if a option should be included in the combo box list.

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.

allowsEmptyCollection-

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

style-

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

render-

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.
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.

ListBoxItem