4.32.2

Select

Find matching results for quick selection or suggested search

Demo

const foodOptions = [ { label: "Apple", value: "apple" }, { label: "Banana", value: "banana", }, { label: "Cucumber", value: "cucumber" }, { label: "Durian", value: "durian" }, { label: "Eggplant", value: "eggplant", disabled: true }, { label: "Fennel", value: "fennel" } ]; const pizzaOptions = [ { label: "Anchovies", value: "anchovies" }, { label: "Olives", value: "olives", selected: true }, { label: "Onion", value: "onion" }, { label: "Pepperoni", value: "pepperoni" }, { label: "Tomatoes", value: "tomatoes" } ]; const foodSelect = document.querySelector("[inputid='food-input']"); const pizzaSelect = document.querySelector("[inputid='pizza-input']"); foodSelect.optionsList = foodOptions; pizzaSelect.optionsList = pizzaOptions;

API

Tag

Name Description
<s-select> Custom Element, accepts content

Methods

Name Description
deselectAll() Call this method to deselect all currently selected items (can be used with multi-select or single select with the selectionoptional attribute)
selectAll() Call this method to select all items (can only be used with multi-select)
getValue() This method returns a Promise that resolves to the select's value (single select returns a string; multi-select returns an array of strings)
close() Call this method to close the select (can only be used with multi-select)

Slots

Name Required Description
no-matches

HTML content that is displayed when no matches are found (if omitted, default content will display). Custom no matches content can be dynamically displayed or hidden by adding or removing class="hidden" on <div slot="no-matches">

Attributes

Name Value Required Description
inputid String

Must be unique per select. Used to generate an id for the input inside the s-select component. You must also provide a for attribute on the label associated with the s-select.

nosearch Boolean

Renders the select with no search input in the dropdown. Mimics native <select> behavior.

multiple Boolean

Gives the s-select multi-select functionality

showselectioncount Boolean

Shows selection count in select trigger instead of individual selection tags (multi-select only)

disabled Boolean

Disables the native <input>.

async Boolean

Enables the s-select to set options asynchronously, see Guidelines below.

loading Boolean

Renders loading indicator in place of results - recommended for asynchronous operations expected to take 2+ seconds.

lazyload Boolean

Use in conjunction with async to enable lazy-loading behavior. See Guidelines for a working example.

loadingnewpage Boolean

Use only in a select with the lazyload attribute. Renders loading indicator below results - required when options are actively being lazy-loaded.

placeholder String

Sets input's placeholder in multi-select.

selectionoptional Boolean

Enables single select to have no selected option.

predictivesearch Boolean

Enables predictive search in results list (component searches entire result label by default; predictive search matches only the beginning of the result label).

replacealloptions Boolean

Enables all options to be replaced in a single select when optionsList is set (by default, single select retains current selection when optionsList is replaced).

optionslist String

Stringified JSON array of option objects. See Guidelines below.

option[selected] Boolean

Indicates option(s) that will be marked as selected when s-select is created.

option[disabled] Boolean

Indicates disabled option(s).

i18n string

A stringified JSON object which defines a list of localized strings. The keys must be one of the string IDs defined below.

Classes

Name Description
success Applies success styling and shows input-msg - see input page for more information
warning Applies warning styling and shows input-msg - see input page for more information
error Applies error styling and shows input-msg - see input page for more information

Properties

Name Value Required Description
inputId String

Must be unique per select. Used to generate an id for the input inside the s-select component. You must also provide a for attribute on the label associated with the s-select.

noSearch Boolean

Renders the select with no search input in the dropdown. Mimics native <select> behavior.

multiple Boolean

Gives the s-select multi-select functionality

showSelectionCount Boolean

Shows selection count in select trigger instead of individual selection tags (multi-select only)

disabled Boolean

Disables the native <input>.

async Boolean

Enables the s-select to set options asynchronously, see Guidelines below.

loading Boolean

Renders loading indicator in place of results - recommended for asynchronous operations expected to take 2+ seconds.

lazyLoad Boolean

Use in conjunction with async to enable lazy-loading behavior. See Guidelines for a working example.

loadingNewPage Boolean

Use only in a select with the lazyLoad prop. Renders loading indicator below results - required when options are actively being lazy-loaded.

placeholder String

Sets input's placeholder in multi-select.

selectionOptional Boolean

Enables single select to have no selected option.

predictiveSearch Boolean

Enables predictive search in results list (component searches entire result label by default; predictive search matches only the beginning of the result label).

replaceAllOptions Boolean

Enables all options to be replaced in a single select when optionsList is set (by default, single select retains current selection when optionsList is replaced).

optionsList Array

Array of option objects. See Guidelines below.

data-input-* string

Used to generate an attribute for the input inside the Select component. e.g. data-input-aria-describedby, data-input-aria-invalid.

filterFunction ({ item: OptionsData, query: string }) => boolean

A function that takes an item object (of type OptionsData) and a query string and returns a boolean. The function must return true if an item should be displayed in the s-select results based on the current query. See Guidelines for an example function.

i18n object

A JSON object which defines a list of localized strings. The keys must be one of the string IDs defined below.

Events

Name Detail Description
s-select

The selectInputId is available on e.detail. The selected option's value and label are available on e.detail.item. If the s-select data is provided as an array of objects rather than as <option> children, the selected object will be available on e.detail.item. e.detail.previousSelection contains the previously selected item, if any (single select only).

Fired after a result is selected.

s-deselect

The selectInputId is available on e.detail. The deselected option's value and label are available on e.detail.item. The isDeselectAll: true flag will also be present on e.detail if this event was fired as part of a deselectAll() call. If the s-select data is provided as an array of objects rather than as <option> children, the deselected object will be available on e.detail.item.

Fired after a result is deselected in a multi-select.

s-error

The selectInputId and errorMessage are available on e.detail.

Fired if an invalid value is typed into the input and then the s-select is closed.

s-input

The selectInputId and inputValue are available on e.detail.

Fired every time the value of the <input> associated with a s-select is changed. See Guidelines below for information on using this event to retrieve options from an external data source.

s-open

The selectInputId is available on e.detail.

Fired when the s-select is opened.

s-close

The selectInputId is available on e.detail.

Fired when the s-select is closed.

s-loadmore

The selectInputId is available on e.detail.

Fired when a user scrolls to the bottom of a lazyload select's results list. See Guidelines for an example of handling this event.

Demo

API

Tag

Name
<SSelect>

Methods

Name Description
deselectAll() Call this method to deselect all currently selected items (can be used with multi-select or single select with the selectionoptional attribute). See the React implementation notes below for more information on calling this method.
selectAll() Call this method to select all items (can only be used with multi-select). See the React implementation notes below for more information on calling this method.
getValue() This method returns a Promise that resolves to the select's value (single select returns a string; multi-select returns an array of strings)
close() Call this method to close the select (can only be used with multi-select)

Slots

Name Required Description
no-matches

HTML content that is displayed when no matches are found (if omitted, default content will display). Custom no matches content can be dynamically displayed or hidden by adding or removing class="hidden" on <div slot="no-matches">

Props

Name Value Required Description
inputId String

Must be unique per select. Used to generate an id for the input inside the Select component. You must also provide a for attribute on the label associated with the Select.

multiple Boolean

Gives the Select multi-select functionality

noSearch Boolean

Renders the Select with no search input in the dropdown. Mimics native <select> behavior.

showSelectionCount Boolean

Shows selection count in select trigger instead of individual selection tags (multi-select only)

async Boolean

Enables the Select to set options asynchronously, see Guidelines above.

loading Boolean

Renders loading indicator in place of results - recommended for asynchronous operations expected to take 2+ seconds.

lazyLoad Boolean

Use in conjunction with async to enable lazy-loading behavior. See Guidelines for a working example.

loadingNewPage Boolean

Use only in a select with the lazyLoad prop. Renders loading indicator below results - required when options are actively being lazy-loaded.

placeholder String

Sets input's placeholder in multi-select.

selectionOptional Boolean

Enables single select to have no selected option.

predictiveSearch Boolean

Enables predictive search in results list (component searches entire result label by default; predictive search matches only the beginning of the result label).

replacealloptions Boolean

Enables all options to be replaced in a single select when optionsList is set (by default, single select retains current selection when optionsList is replaced).

disabled Boolean

Disables the component.

optionsList Array

Array of option objects. See Guidelines above for information on the structure of these objects.

data-input-* string

Used to generate an attribute for the input inside the Select component. e.g. data-input-aria-describedby, data-input-aria-invalid.

filterFunction ({ item: OptionsData, query: string }) => boolean

A function that takes an item object (of type OptionsData) and a query string and returns a boolean. The function must return true if an item should be displayed in the s-select results based on the current query. See Guidelines for an example function.

i18n object

A JSON object which defines a list of localized strings. The keys must be one of the string IDs defined below.

onS-select Function

Handles the s-select event fired after a result is selected. The selectInputId is available on e.detail. The selected option's value, label, and any other app-defined values are available on e.detail.item. e.detail.previousSelection contains the previously selected item, if any (single select only).

onS-deselect Function

Handles the s-deselect event fired after a result is deselected in a multi-select. The selectInputId is available on e.detail. The isDeselectAll: true flag will also be present on e.detail if this event was fired as part of a deselectAll() call. The deselected option's value, label, and any other app-defined values are available on e.detail.item.

onS-error Function

Handles the s-error event fired if an invalid value is typed into the input and then the Select is closed. The selectInputId and errorMessage are available on e.detail.

onS-input Function

Handles the s-input event, which is fired every time the value of the <input> associated with a Select is changed. The selectInputId and inputValue are available on e.detail. See Guidelines above for information on using this event to retrieve options from an external data source.

onS-open Function

Handles the s-open event fired after the Select is opened. The selectInputId is available on e.detail.

onS-close Function

Handles the s-close event fired after the Select is closed. The selectInputId is available on e.detail.

onS-loadmore

The selectInputId is available on e.detail.

Handles the s-loadmore event fired when a user scrolls to the bottom of a lazyLoad select's results list. See Guidelines for an example of handling this event.

Classes

Name Description
success Applies success styling and shows input-msg - see input page for more information
warning Applies warning styling and shows input-msg - see input page for more information
error Applies error styling and shows input-msg - see input page for more information

React implementation notes

Default selected options

If you are using <option> children rather than the JSON API, do not use the selected attribute to set default selected options. Use the defaultValue prop:

    
    <SSelect
      defaultValue={} // string or array of strings, representing options' values
    >
      {options} 
    </SSelect>
    
    

Using refs to call Select method

In order to call the deselectAll() method, you must create a ref, assign it to the Select, and then use ref.current to access the method:

    
    const selectRef = React.createRef(); 
    
    function deselectAll() {
      selectRef.current.deselectAll();
    }
    
    return (
      <SSelect ref={selectRef} />
    )
    
    

Using refs to access SSelect value

In order to get the current value of the SSelect, you must create a ref, assign it to the SSelect, and then call getValue() on ref.current. The getValue method returns a promise which resolves to the select's value.

    
    const selectRef = React.createRef(); 
    
    function returnValue() {
      selectRef.current.getValue().then((value) => console.log(value));
    }
    
    return (
      <SSelect ref={selectRef} />
    )
    
    

Skylab React links

General information about using our React package

Typescript

Exported types

// Object provided (in array) to optionsList prop export type OptionsData = { label: string; value: string; selected?: boolean; disabled?: boolean; }; // s-deselect event's e.detail export type SDeselectItem = { selectInputId: string; item: OptionsData; isDeselectAll: boolean }; // s-select event's e.detail export type SSelectItem = { selectInputId: string; item: OptionsData; previousSelection: null | OptionsData }; // s-close event's e.detail export type SCloseItem = { selectInputId: string }; // s-open event's e.detail export type SOpenItem = { selectInputId: string }; // s-error event's e.detail export type SErrorItem = { selectInputId: string; errorMessage: string }; // s-input event's e.detail export type SInputItem = { inputValue: string; selectInputId: string };

i18n Strings

ID Description Default value
"select.selectionAnnouncement" The text announced by screen readers when a multi-select chip is focused. Must include the string {SELECTED_ITEM} as a placeholder. {SELECTED_ITEM} selected. Press delete to deselect.
"select.noMatches" The default text shown when no matches are found. No matches found
"select.selectionCountSingular" The text shown in a multi-select containing one selection. Must contain the string {SELECTION_NUMBER} as a placeholder. {SELECTION_NUMBER} selection
"select.selectionCountPlural" The text shown in a multi-select containing multiple selections. Must contain the string {SELECTION_NUMBER} as a placeholder. {SELECTION_NUMBER} selections
"select.ariaLabel.dismiss" The aria-label on the dismiss button in a multi-select chip. Dismiss
"select.ariaLabel.deselectAll" The aria-label used for the "Deselect all" icon button. Deselect all

Guidelines

Accessibility

Each Select must have an associated label with for=<inputid> and a unique id. The id will be passed in to the aria-labelledby attribute on the Select to ensure that screen readers present it properly.

Example filterFunction

This example function will display an s-select option item if the search query matches any part of the item's value (by default, an item is shown if the query matches any part of the item's label). Don't forget to use toLowerCase() to make the search case-insensitive.

function exampleFilterFunction({ item, query }) { return item.value.toLowerCase().trim().includes(query.toLowerCase().trim()); }

Creating Select sources

If you will be dynamically updating select options during the Select component's lifetime, do not use <option> children. You should set the optionsList property on s-select (or the optionsList prop on SSelect) to an array of objects after the component is instantiated, or assign a stringified JSON array of option objects to the optionslist attribute. The objects in the array will have these properties:

An example of assigning the optionsList object to the s-select:

const danceSelect = document.querySelector("s-select[inputid='dance-input']"); danceSelect.optionsList = [{ label: "Salsa", value: "salsa", selected: true }, { label: "Tango", value: "tango" }, { label: "Waltz", value: "waltz", disabled: true }];

Default options

The default option in a single select should be given the boolean selected attribute. If no option is marked as selected, the first item will be selected by default in single selects. In a multi-select, there will not be a default selection defined if no option is marked as selected.

Option IDs

Unique id values are generated for each select option, based on the id of the s-select (a random number) and the value of the option. Each option's value must be unique.

Validation

Validation can be performed within the consuming app. If validation fails, add the error class to s-select and include input-msg as indicated in code sample above (see input page for further information on messaging). The consuming app is responsible for all validation messaging.

Async options

For some use cases, it may be necessary to retrieve options from an external data source based on user input. This can be accomplished by assigning the component the async attribute and listening to the s-input event. If the asynchronous operation is expected to take longer than 2 seconds to execute, attach the loading attribute to the component while retrieving data. Use the s-input event handler to populate the options using a pattern similar to the example below:

const asyncSelect = document.getElementById('async-select'); asyncSelect.addEventListener('s-input', function (e) { if (e.detail.inputValue.toLowerCase() === 'opt') { asyncSelect.setAttribute('loading', ''); const exampleOptions = [ { label: "Option 1", value: "option-1" }, { label: "Option 2", value: "option-2" }, { label: "Opt 3", value: "option-3" }, { label: "Opt 4", value: "option-4" }, { label: "Longer option 5", value: "option-5" }, { label: "Longer option 6", value: "option-6" }, ] setTimeout(() => { asyncSelect.optionsList = exampleOptions asyncSelect.removeAttribute('loading'); }, 2000) } if (e.detail.inputValue.toLowerCase() === 'val') { asyncSelect.setAttribute('loading', ''); const exampleOptions = [ { label: "Value 1", value: "value-1" }, { label: "Value 2", value: "value-2" }, { label: "Val 3", value: "value-3" }, { label: "Val 4", value: "value-4" }, { label: "Longer value 5", value: "value-5" }, { label: "Longer value 6", value: "value-6" }, ] setTimeout(() => { asyncSelect.optionsList = exampleOptions asyncSelect.removeAttribute('loading'); }, 2000) } })

Lazy loading

Use the lazyload attribute in conjunction with async to enable lazy loading behavior in the select. The component will emit the s-loadmore event when the user scrolls to the bottom of the results dropdown, indicating to the consuming app that the next set of options can be added to the optionsList. The app MUST add the loadingnewpage attribute before loading new options, and remove the attribute when loading is finished, in order for the new options to display correctly.

function generateSelectOptions(startIndex, length) { const options = []; for(let i = startIndex; i <= startIndex + length; i++) { options.push({ label: `${i}`, value: `option-${i}` }); } return options; } function handleSLoadmore(event) { const { selectInputId } = event.detail; const selectElement = document.querySelector(`[inputid='${selectInputId}']`); const optionsLength = selectElement.optionsList.length; selectElement.loadingNewPage = true; const numToLoad = 10; const newOptions = generateSelectOptions(optionsLength, numToLoad); const currentOptions = selectElement.optionsList; setTimeout(() => { selectElement.optionsList = [...currentOptions, ...newOptions]; selectElement.loadingNewPage = false; }, 1000); } const lazyLoadSelect = document.querySelector('[inputid="lazy-load-select-input"]'); lazyLoadSelect.addEventListener('s-loadmore', handleSLoadmore);

Design

Design resources can be found on the Skylab design documentation site: skylab.avalara.com