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>
    )}
/>
         

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.