ToggleButton

ToggleButton is used to select a boolean value using a button.


import { ToggleButton } from 'primereact/togglebutton';
         

ToggleButton is used a controlled input component with value and onChange properties.

No

<ToggleButton checked={checked} onChange={(e) => setChecked(e.value)} />
         

Icons and Labels can be customized using onLabel, offLabel, onIcon and offIcon properties.

I reject

<ToggleButton onLabel="I confirm" offLabel="I reject" onIcon="pi pi-check" offIcon="pi pi-times" 
    checked={checked} onChange={(e) => setChecked(e.value)} />
         
Compatibility with popular React form libraries.

Formik is a popular library for handling forms in React.

No
 

<ToggleButton id="item"
    name="item"
    checked={formik.values.item}
    onChange={(e) => {
        formik.setFieldValue('item', e.value);
    }}
    className={classNames('w-6rem', { 'p-invalid': formik.errors.item })}
/>
{getFormErrorMessage('item')}
<Button label="Submit" type="submit" icon="pi pi-check" />
         

React Hook Form is another popular React library to handle forms.

No
 

<Controller
    name="value"
    control={form.control}
    rules={{ required: 'Value is required.' }}
    render={({ field, fieldState }) => (
        <div className="flex flex-column align-items-center gap-2">
            <ToggleButton id={field.name} checked={field.value} onChange={field.onChange} className={classNames('w-6rem', { 'p-invalid': fieldState.error })} />
            {getFormErrorMessage(field.name)}
        </div>
    )}
/>
         

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

NameElement
p-togglebuttonContainer element
p-button-icon-leftIcon element.
p-button-textLabel element.
Accessibility guide documents the specification of this component based on WCAG guidelines, the implementation is in progress.

Screen Reader

ToggleButton component uses an element with button role and updates aria-pressed state for screen readers. Value to describe the component can be defined with aria-labelledby or aria-label props, it is highly suggested to use either of these props as the component changes the label displayed which will result in screen readers to read different labels when the component receives focus. To prevent this, always provide an aria label that does not change related to state.


<span id="rememberme">Remember Me</span>
<ToggleButton aria-labelledby="rememberme" />

<ToggleButton aria-label="Remember Me" />
     

Keyboard Support

KeyFunction
tabMoves focus to the button.
spaceToggles the checked state.
Visit the API documentation for detailed information about all the properties, events and methods of the component.