lara-light-indigo

Dropdown

Dropdown also known as Select, is used to choose an item from a collection of options.

Import via Module

import { Dropdown } from 'primereact/dropdown';
 
Import via CDN

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

SelectButton 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'}
];
 

<Dropdown value={city} options={citySelectItems} onChange={(e) => setCity(e.value)} placeholder="Select a City"/>
 

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'}
];
 

<Dropdown optionLabel="name" value={city} options={cities} onChange={(e) => setCity(e.value)} placeholder="Select a City"/>
<Dropdown optionLabel="name" optionValue="code" value={city} options={cities} onChange={(e) => setCity(e.value)} placeholder="Select a City"/>
 

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

Placeholder

Common pattern is providing an empty option as the placeholder when using native selects, however Dropdown has built-in support using the placeholder option so it is suggested to use it instead of creating an empty option.

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


<Dropdown value={selectedCountry} options={countries} onChange={(e) => setSelectedCountry(e.value)} optionLabel="name" filter showClear filterBy="name"
    placeholder="Select a Country" itemTemplate={countryOptionTemplate} />
 
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.


<Dropdown value={selectedCountry} options={countries} onChange={(e) => setSelectedCountry(e.value)} optionLabel="name" placeholder="Select a Country"
    valueTemplate={selectedCountryTemplate} itemTemplate={countryOptionTemplate} filter filterTemplate={filterTemplate}/>
 

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

const selectedCountryTemplate = (option, props) => {
    if (option) {
        return (
            <div className="country-item country-item-value">
                <img alt={option.name} src="images/flag/flag_placeholder.png" className={`flag flag-${option.code.toLowerCase()}`} />
                <div>{option.name}</div>
            </div>
        );
    }

    return (
        <span>
            {props.placeholder}
        </span>
    );
}

const countryOptionTemplate = (option) => {
    return (
        <div className="country-item">
            <img alt={option.name} src="images/flag/flag_placeholder.png" className={`flag flag-${option.code.toLowerCase()}`} />
            <div>{option.name}</div>
        </div>
    );
}

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);
}
 
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' }
        ]
    }
];
 

<Dropdown value={selectedGroupedCity} options={groupedCities} onChange={e => setSelectedGroupedCity(e.value)} optionLabel="label" optionGroupLabel="label" optionGroupChildren="items" />
 
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.
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.
valueanynullValue of the component.
optionsarraynullAn array of selectitems to display as the available options.
optionLabelstringnullName of the label field of an option when arbitrary objects are used as options instead of SelectItems.
optionValuestringnullName of the value field of an option when arbitrary objects are used as options instead of SelectItems.
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.
valueTemplateanynullThe template of selected item.
itemTemplateanynullThe template of items.
filterTemplateanynullThe template of filter element.
optionGroupTemplateanynullTemplate of an option group item.
stylestringnullInline style of the element.
classNamestringnullStyle class of the element.
scrollHeightstring200pxHeight of the viewport in pixels, a scrollbar is defined if height of list exceeds this value.
filterbooleanfalseWhen 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.
emptyMessagestringNo results foundText to display when there are no options available.
emptyFilterMessageanyNo results foundTemplate to display when filtering does not return any results.
resetFilterOnHidebooleanfalseClears the filter value when hiding the dropdown.
editablebooleanfalseWhen present, custom value instead of predefined options can be entered using the editable input field.
placeholderstringnullDefault text to display when no option is selected.
requiredbooleanfalseWhen present, it specifies that an input field must be filled out before submitting the form.
disabledbooleanfalseWhen present, it specifies that the component should be disabled.
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.
tabIndexnumbernullIndex of the element in tabbing order.
autoFocusbooleanfalseWhen present, it specifies that the component should automatically get focus on load.
filterInputAutoFocusbooleantrueWhen the panel is opened, it specifies that the filter input should focus automatically.
showFilterClearbooleanfalseWhen enabled, a clear icon is displayed to clear the filtered value.
panelClassNamestringnullStyle class of the overlay panel element.
panelStyleobjectnullInline style of the overlay panel element.
dataKeystringnullA property to uniquely match the value in options for better performance.
inputIdstringnullIdentifier of the focusable input.
showClearbooleanfalseWhen enabled, a clear icon is displayed to clear the value.
maxLengthnumbernullMaximum number of characters to be typed on an editable input.
tooltipanynullContent of the tooltip.
tooltipOptionsobjectnullConfiguration of the tooltip, refer to the tooltip documentation for more information.
ariaLabelstringfalseUsed to define a string that labels the component.
ariaLabelledBystringnullContains the element IDs of labels.
transitionOptionsobjectnullThe properties of CSSTransition can be customized, except for "nodeRef" and "in" properties.
dropdownIconstringpi pi-chevron-downIcon class of the dropdown icon.
showOnFocusbooleanfalseWhen enabled, overlay panel will be visible with input focus.
virtualScrollerOptionsobjectnullWhether to use the virtualScroller feature. The properties of VirtualScroller component can be used like an object in it.
Events
NameParametersDescription
onChangeevent.originalEvent: Original event
event.value: Value of the checkbox
Callback to invoke on value change
onMouseDownevent: Browser eventCallback to invoke to when a mouse button is pressed.
onContextMenuevent: Browser eventCallback to invoke on right-click.
onFocusevent: Browser event.Callback to invoke when the element receives focus.
onBlurevent: Browser event.Callback to invoke when the element loses focus.
onFilterevent.originalEvent: Original event
event.filter: Value of the filter input
Callback to invoke when the value is filtered.
Methods
NameParametersDescription
checkValidity-Checks whether the native hidden select element has any constraints and returns a boolean for the result.
resetFilter-Reset the options filter.
onShow-Callback to invoke when overlay panel becomes visible.
onHide-Callback to invoke when overlay panel becomes hidden.
Styling

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

NameElement
p-dropdownContainer element.
p-dropdown-labelElement to display label of selected option.
p-dropdown-triggerIcon element.
p-dropdown-panelIcon element.
p-dropdown-items-wrapperWrapper element of items list.
p-dropdown-itemsList element of items.
p-dropdown-itemAn item in the list.
p-dropdown-filter-containerContainer of filter input.
p-dropdown-filterFilter element.
p-dropdown-openContainer element when overlay is visible.
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