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.
<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.
<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.
Name | Element |
---|---|
p-inputswitch | Container element. |
p-inputswitch-checked | Container element in active state. |
p-inputswitch-slider | Slider element behind the handle. |
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" />
Key | Function |
---|---|
tab | Moves focus to the switch. |
space | Toggles the checked state. |