React SelectButton

React SelectButton

·

3 min read

React SelectButton is used to choose single or multiple items from a list using buttons.

Setup

Refer to PrimeReact setup documentation for download and installation steps for your environment.

Import

import { SelectButton } from 'primereact/selectbutton';

Getting Started

Dropdown 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'}
];
<SelectButton value={city} options={citySelectItems} onChange={(e) => setValue(e.value)}></SelectButton>

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'}
];
<SelectButton optionLabel="name" value={city} options={cities} onChange={(e) => setValue(e.value)}></SelectButton>
<SelectButton optionLabel="name" optionValue="code" value={city} options={cities} onChange={(e) => setValue(e.value)}></SelectButton>

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

Multiple

SelectButton allows selecting only one item by default and setting multiple option enables choosing more than one item. In multiple case, model property should be an array.

Custom Content

Options support templating using the itemTemplate property that references a function to render the content. Notice the usage of optionLabel, although it is not rendered visually, it is still required to be used as the list key.

<SelectButton optionLabel="name" optionValue="code" value={city} options={cities} onChange={(e) => setValue(e.value)} itemTemplate={itemTemplate} />
const itemTemplate = (option) => {
    // custom item content
}

Theming

SelectButton supports various themes featuring Material, Bootstrap, Fluent as well as your own custom themes via the Designer tool.

Resources

Visit the PrimeReact SelectButton showcase for demos and documentation.