lara-light-indigo

MultiSelect

MultiSelect is used to select multiple items from a collection.

Basic
Select a City
Chips
Select a City
Grouped
Select Cities
Advanced with Templating and Filtering
Select Countries
Virtual Scroll (100000 Items)
Select Item
Virtual Scroll (100000 Items) and Lazy
Select Item
Import via Module

import { MultiSelect } from 'primereact/multiselect';
 
Import via CDN

<script src="https://unpkg.com/primereact/core/core.min.js"></script>
<script src="https://unpkg.com/primereact/multiselect/multiselect.min.js"></script>
 
Getting Started

MultiSelect is used as a controlled component with value and onChange properties along with the options collection. There are two alternatives of how to define the options property; One way is providing a collection of SelectItem instances having label-value pairs whereas other way is providing an array of arbitrary objects along with the optionLabel and optionValue properties to specify the label/value field pair. In addition, options can be simple primitive values such as a string array, in this case no optionLabel or optionValue is necessary.

Options as SelectItems


const citySelectItems = [
    {label: 'New York', value: 'NY'},
    {label: 'Rome', value: 'RM'},
    {label: 'London', value: 'LDN'},
    {label: 'Istanbul', value: 'IST'},
    {label: 'Paris', value: 'PRS'}
];
 

<MultiSelect value={cities} options={citySelectItems} onChange={(e) => setCities(e.value)} />
 

Options as any type


const cities = [
    {name: 'New York', code: 'NY'},
    {name: 'Rome', code: 'RM'},
    {name: 'London', code: 'LDN'},
    {name: 'Istanbul', code: 'IST'},
    {name: 'Paris', code: 'PRS'}
];
 

<MultiSelect optionLabel="name" value={cities} options={cities} onChange={(e) => setCities(e.value)} />
<MultiSelect optionLabel="name" optionValue="code" value={cities} options={cities} onChange={(e) => setCities(e.value)} />
 

When optionValue is not defined, value of an option refers to the option object itself.

Chips Display

A comma separated list is used by default to display selected items whereas alternative chip mode is provided using the display property to visualize the items as tokens.


<MultiSelect display="chip" optionLabel="name" value={selectedCities} options={cities} onChange={(e) => setSelectedCities(e.value)} />
 
Custom Content

Label of an option is used as the display text of an item by default, for custom content support define an itemTemplate function that gets the option instance as a parameter and returns the content. For custom filter support define a filterTemplate function that gets the option instance as a parameter and returns the content for the filter element.


<MultiSelect value={cities} options={citySelectItems} onChange={(e) => setCities(e.value)} itemTemplate={itemTemplate} filter filterTemplate={filterTemplate}/>
 

const [filterValue, setFilterValue] = useState('');
const filterInputRef = useRef();

itemTemplate(option) {
    // custom item content
}

const filterTemplate = (options) => {
    let {filterOptions} = options;

    return (
        <div className="flex gap-2">
            <InputText value={filterValue} ref={filterInputRef} onChange={(e) => myFilterFunction(e, filterOptions)} />
            <Button label="Reset" onClick={() => myResetFunction(filterOptions)} />
        </div>
    )
}

const myResetFunction = (options) => {
    setFilterValue('');
    options.reset();
    filterInputRef && filterInputRef.current.focus()
}

const myFilterFunction = (event, options) => {
    let _filterValue = event.target.value;
    setFilterValue(_filterValue);
    options.filter(event);
}
 

selectedItemTemplate can be used to customize the selected values display instead of the default comma separated list.


<MultiSelect value={cities} options={citySelectItems} onChange={(e) => setCities(e.value)} selectedItemTemplate={selectedItemTemplate} />
 

selectedItemTemplate(option) {
    // custom selected item content
}
 

In addition panelHeaderTemplate and panelFooterTemplate can be used to customize the header and footer of panel.


<MultiSelect value={cities} options={citySelectItems} onChange={(e) => setCities(e.value)} panelHeaderTemplate={panelHeaderTemplate} panelFooterTemplate={panelFooterTemplate} />
 

panelHeaderTemplate(options) {
    // options.className: Style class of the panel header.
    // options.checkboxElement: Default checkbox element created by the component.
    // options.checked: Whether the all checkbox is checked.
    // options.onChange: Change event of toggleable checkbox.
    // options.filterElement: Default filter element created by the component.
    // options.closeElement: Default close element created by the component.
    // options.closeElementClassName: Style class of the close container
    // options.closeIconClassName: Style class of the close icon
    // options.onCloseClick: Click event for the close icon.
    // options.element: Default element created by the component.
    // options.props: component props.
}

panelFooterTemplate(options) {
    // options.props: component props.
}
 
Grouping

Options groups are specified with the optionGroupLabel and optionGroupChildren properties.


const groupedCities = [
    {
        label: 'Germany', code: 'DE',
        items: [
            { label: 'Berlin', value: 'Berlin' },
            { label: 'Frankfurt', value: 'Frankfurt' },
            { label: 'Hamburg', value: 'Hamburg' },
            { label: 'Munich', value: 'Munich' }
        ]
    },
    {
        label: 'USA', code: 'US',
        items: [
            { label: 'Chicago', value: 'Chicago' },
            { label: 'Los Angeles', value: 'Los Angeles' },
            { label: 'New York', value: 'New York' },
            { label: 'San Francisco', value: 'San Francisco' }
        ]
    },
    {
        label: 'Japan', code: 'JP',
        items: [
            { label: 'Kyoto', value: 'Kyoto' },
            { label: 'Osaka', value: 'Osaka' },
            { label: 'Tokyo', value: 'Tokyo' },
            { label: 'Yokohama', value: 'Yokohama' }
        ]
    }
];
 

<MultiSelect value={selectedGroupedCities} options={groupedCities} onChange={(e) => setSelectedGroupedCities(e.value)} optionLabel="label" optionGroupLabel="label" optionGroupChildren="items" />
 
Filtering

Options can be filtered using an input field in the overlay by enabling the filter property. By default filtering is done against label of the items and filterBy property is available to choose one or more properties of the options. In addition filterMatchMode can be utilized to define the filtering algorithm, valid options are "contains" (default), "startsWith", "endsWith", "equals" and "notEquals".


<MultiSelect value={cities} options={citySelectItems} onChange={(e) => setCities(e.value)} filter/>
 
SelectItem API
NameTypeDefaultDescription
labelstringnullLabel of the option.
valuestringnullValue of the option.
classNamestringnullClassName of the option.
titlestringnullTooltip text of the option. (Not supported)
disabledbooleanfalseWhether the option is disabled or not. (Not supported)
Properties

Any valid attribute is passed to the root element implicitly, extended properties are as follows;

NameTypeDefaultDescription
idstringnullUnique identifier of the element.
namestringnullName of the input element.
valuearraynullValue of the component.
optionsarraynullAn array of selectitems to display as the available options.
optionLabelstringnullName of the label field of an option when an arbitrary objects instead of SelectItems are used as options.
optionValuestringnullProperty name or getter function to use as the value of an option, defaults to the option itself when not defined.
optionDisabledfunction | stringnullProperty name or getter function to use as the disabled flag of an option, defaults to false when not defined.
optionGroupLabelstringnullProperty name or getter function to use as the label of an option group.
optionGroupChildrenstringnullProperty name or getter function that refers to the children options of option group.
stylestringnullInline style of the element.
classNamestringnullStyle class of the element.
panelClassNamestringnullStyle class of the overlay panel element.
panelStylestringnullInline style of the overlay panel element.
scrollHeightstring200pxHeight of the viewport in pixels, a scrollbar is defined if height of list exceeds this value.
placeholderstringnullLabel to display when there are no selections.
fixedPlaceholderbooleanfalseWhether to display selected items in the label section or always display the placeholder as the default label.
disabledbooleanfalseWhen present, it specifies that the component should be disabled.
showClearbooleanfalseWhen enabled, a clear icon is displayed to clear the value.
filterbooleantrueWhen specified, displays an input field to filter the items on keyup.
filterBystringlabelWhen filtering is enabled, filterBy decides which field or fields (comma separated) to search against.
filterMatchModestringcontainsDefines how the items are filtered, valid values are "contains", (default) "startsWith", "endsWith", "equals" and "notEquals".
filterPlaceholderstringnullPlaceholder text to show when filter input is empty.
filterLocalestringundefinedLocale to use in filtering. The default locale is the host environment's current locale.
emptyFilterMessageanyNo records foundTemplate to display when filtering does not return any results.
resetFilterOnHidebooleanfalseClears the filter value when hiding the dropdown.
tabIndexnumbernullIndex of the element in tabbing order.
dataKeystringnullA property to uniquely match the value in options for better performance.
inputIdstringnullIdentifier of the focusable input.
tooltipanynullContent of the tooltip.
tooltipOptionsobjectnullConfiguration of the tooltip, refer to the tooltip documentation for more information.
itemTemplatefunctionnullFunction that gets the option and returns the content for it.
filterTemplateanynullThe template of filter element.
optionGroupTemplateanynullTemplate of an option group item.
selectedItemTemplatefunctionnullFunction that gets an item in the value and returns the content for it.
panelHeaderTemplateanynullTemplate of the panel header.
panelFooterTemplateanynullTemplate of the panel footer.
appendToDOM element | stringdocument.bodyDOM element instance where the overlay panel should be mounted. Valid values are any DOM Element and 'self'. The self value is used to render a component where it is located.
maxSelectedLabelsnumbernullDecides how many selected item labels to show at most.
selectionLimitnumbernullNumber of maximum options that can be selected.
selectedItemsLabelstring{0} items selectedLabel to display after exceeding max selected labels.
ariaLabelledBystringnullEstablishes relationships between the component and label(s) where its value should be one or more element IDs.
displaystringcommaUsed mode to display the selected item. Valid values are 'comma' and 'chip'.
transitionOptionsobjectnullThe properties of CSSTransition can be customized, except for "nodeRef" and "in" properties.
dropdownIconanypi pi-chevron-downIcon class of the dropdown icon.
removeIconanypi pi-times-circleIcon of the remove chip element.
virtualScrollerOptionsobjectnullWhether to use the virtualScroller feature. The properties of VirtualScroller component can be used like an object in it.
showSelectAllbooleantrueWhether to show the select all checkbox inside the panel's header.
selectAllbooleanfalseWhether all data is selected.
Events
NameParametersDescription
onChangeevent.originalEvent: Browser event
event.value: Current selected values
Callback to invoke when value changes.
onFocusevent: Browser event.Callback to invoke when the element receives focus.
onBlurevent: Browser event.Callback to invoke when the element loses focus.
onShow-Callback to invoke when overlay panel becomes visible.
onHide-Callback to invoke when overlay panel becomes hidden.
onFilterevent.originalEvent: Browser event
event.filter: Filter value.
Callback to invoke on filtering.
onSelectAllevent.originalEvent: Browser event
event.checked: Whether all data is selected.
Callback to invoke when all data is selected.
Methods
NameParametersDescription
checkValidity-Checks whether the native hidden input element has any constraints and returns a boolean for the result.
Styling

Following is the list of structural style classes, for theming classes visit theming page.

NameElement
p-multiselectContainer element.
p-multiselect-label-containerContainer of the label to display selected items.
p-multiselect-label-containerLabel to display selected items.
p-multiselect-triggerDropdown button.
p-multiselect-filter-containerContainer of filter input.
p-multiselect-panelOverlay panel for items.
p-multiselect-itemsList container of items.
p-multiselect-itemAn item in the list.
p-multiselect-tokenA selected item element container on display='chip' mode.
p-chips-token-iconIcon of a selected item element on display='chip' mode.
p-chips-token-labelLabel of a selected item element on display='chip' mode.
Accessibility

This section is under development. After the necessary tests and improvements are made, it will be shared with the users as soon as possible.

Dependencies

None.

Component Scale

Input Style

Ripple Effect

Free Themes

Built-in component themes created by the PrimeReact Theme Designer.

Bootstrap
Blue
Purple
Blue
Purple
Material Design
Indigo
Deep Purple
Indigo
Deep Purple
Material Design Compact
Indigo
Deep Purple
Indigo
Deep Purple
Tailwind
Tailwind Light
Fluent UI
Blue
PrimeOne Design - 2022 NEW
Lara Indigo
Lara Blue
Lara Purple
Lara Teal
Lara Indigo
Lara Blue
Lara Purple
Lara Teal
PrimeOne Design - 2021
Saga Blue
Saga Green
Saga Orange
Saga Purple
Vela Blue
Vela Green
Vela Orange
Vela Purple
Arya Blue
Arya Green
Arya Orange
Arya Purple
Premium Themes

Premium themes are only available exclusively for PrimeReact Theme Designer subscribers and therefore not included in PrimeReact core.

Soho Light
Soho Dark
Viva Light
Viva Dark
Mira
Nano

Legacy Free Themes

Nova
Nova Alt
Nova Accent
Luna Blue
Luna Green
Luna Amber
Luna Pink
Rhea

Premium Create-React-App Templates

Beautifully crafted premium create-react-app application templates by the PrimeTek design team.

Sakai
Atlantis
Freya
Ultima
Diamond
Sapphire
Serenity
Babylon
Avalon
Apollo
Roma