InputSwitch

InputSwitch is used to select a boolean value.


import { InputSwitch } from 'primereact/inputswitch';
         

InputSwitch is used as a controlled input with checked and onChange properties.


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

Enabling checked property displays the component as active initially.


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

Invalid state style is added using the p-invalid class to indicate a failed validation.


<InputSwitch className="p-invalid" />
         

When disabled is present, the element cannot be edited and focused.


<InputSwitch disabled />
         

Compatibility with popular React form libraries.

Formik is a popular library for handling forms in React.

I've read and accept the terms & conditions.
 

<Toast ref={toast} />
<InputSwitch
    id="value"
    name="value"
    checked={formik.values.value}
    onChange={(e) => {
        formik.setFieldValue('value', e.value);
    }}
    className={classNames({ 'p-invalid': isFormFieldInvalid('value') })}
/>
{getFormErrorMessage('value')}
<Button type="submit" label="Submit" />
 

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

I've read and accept the terms & conditions. 

<Toast ref={toast} />
<Controller
    name="checked"
    control={control}
    rules={{ required: 'Accept is required.' }}
    render={({ field, fieldState }) => (
        <>
            <label htmlFor={field.name} className={classNames({ 'p-error': errors.checked })}></label>
            <InputSwitch inputId={field.name} checked={field.value} inputRef={field.ref} className={classNames({ 'p-invalid': fieldState.error })} onChange={(e) => field.onChange(e.value)} />
            {getFormErrorMessage(field.name)}
        </>
    )}
/>
         

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

NameElement
p-inputswitchContainer element.
p-inputswitch-checkedContainer element in active state.
p-inputswitch-sliderSlider element behind the handle.
Accessibility guide documents the specification of this component based on WCAG guidelines, the implementation is in progress.

Screen Reader

InputSwitch component uses a hidden native checkbox element with switch role internally that is only visible to screen readers. Value to describe the component can either be provided via label tag combined with inputId prop or using aria-labelledby, aria-label props.


<label htmlFor="switch1">Remember Me</label>
<InputSwitch inputId="switch1" />

<span id="switch2">Remember Me</span>
<InputSwitch aria-labelledby="switch2" />

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

Keyboard Support

KeyFunction
tabMoves focus to the switch.
spaceToggles the checked state.