RHF-MUI Components
NPM

RHFSwitch

RHFSwitch is a single Switch with a boolean value, an inline label, and optional helper text or error state, bound to React Hook Form through control.

Usage

import RHFSwitch, { RHFSwitchProps } from '@nish1896/rhf-mui-components/mui/switch';
import { useForm } from 'react-hook-form';

type FormValues = {
  notifications: boolean;
};

const { control, handleSubmit } = useForm<FormValues>({
  defaultValues: { notifications: false }
});

<form onSubmit={handleSubmit(values => console.log(values))}>
  <RHFSwitch
    fieldName="notifications"
    control={control}
    label="Email notifications"
  />
</form>

The stored value is a boolean. onValueChange receives { newValue, event }: the next checked state and the change event. The label defaults to text generated from fieldName, so notifications becomes "Notifications", and hideLabel removes the visible label.

Label and placement

label accepts any ReactNode. The label sits after the switch by default. formControlLabelProps is forwarded to the FormControlLabel around the switch, so labelPlacement can move it to the 'start', 'top' or 'bottom'. Its sx is merged with the default FormControlLabel styles from ConfigProvider.

<RHFSwitch
  fieldName="darkMode"
  control={control}
  label="Dark mode"
  formControlLabelProps={{
    labelPlacement: 'start',
    sx: { justifyContent: 'space-between', ml: 0 }
  }}
/>

Styling the switch

The remaining SwitchProps are passed to the Switch, for example color, size, edge and sx. slotProps is forwarded too. name, checked and onChange are managed by the component.

<RHFSwitch
  fieldName="notifications"
  control={control}
  color="secondary"
  size="small"
/>

Helper text and errors

A switch can't be invalid by itself, so add a rule in registerOptions. A required rule fails while the switch is off. The message replaces helperText while it is shown.

<RHFSwitch
  fieldName="acceptTerms"
  control={control}
  label="I accept the terms"
  helperText="Required to continue"
  registerOptions={{ required: 'You must accept the terms' }}
/>

Handling value changes

onValueChange runs after the new value has been stored in the form. It receives { newValue, event }:

<RHFSwitch
  fieldName="darkMode"
  control={control}
  onValueChange={({ newValue, event }) => applyTheme(newValue ? 'dark' : 'light')}
/>

Use customOnChange when you need to change what gets stored. It replaces the default handling, so you must call rhfOnChange yourself with the value to store. This example asks for confirmation before turning the switch off: onValueChange is not called when customOnChange is used.

<RHFSwitch
  fieldName="notifications"
  control={control}
  customOnChange={({ rhfOnChange, newValue, event }) => {
    if (newValue || window.confirm('Turn off all notifications?')) {
      rhfOnChange(newValue);
    }
  }}
/>

Examples

API

RHFSwitchProps extends SwitchProps and accepts the following additional props. Props marked with * are required.

NameTypeDescription
fieldName*string
Name of the field registered with React Hook Form. This prop is required for all components.
control*UseFormControl
The control option yielded on calling the useForm hook.
registerOptionsRegisterOptions
React Hook Form validation rules. Useful when not using a schema validation library such as Yup or Joi.
customOnChange({ rhfOnChange, newValue, event }) => void
Override the default onChange behavior of the component. You can also prevent the toggle behaviour using event.preventDefault() based on your business logic, but must pass the updated newValue value to the rhfOnChange function to toggle the field.
onValueChange({ newValue, event }) => void
An optional callback function which returns whether the switch is turned on or not.
labelReactNode
The text to render in the FormLabel component. By default, the value of fieldName is transformed (e.g., "firstName" to "First Name") using the fieldNameToLabel function.
formControlLabelPropsFormControlLabelProps
FormControlLabelProps to customise FormControlLabel component for a field. Multiple fields can be configured using the ConfigProvider component.
hideLabelboolean
Hides the FormLabel component if you don’t want to display the default form label component or prefer to render a fully custom label instead.
renderError(error: FieldError) => ReactNode
Custom renderer for the React Hook Form field error. Receives the current field error and returns the content to display, such as error.message or a custom React element in the HelperText component.
Added in v4.1.0.
hideErrorMessageboolean
A flag to prevent replacement of helper text of a field by the errorMessage when the validation is triggered.
helperTextReactNode
The content to display within the FormHelperText component below the field. If the field validation fails, this content will be overridden by the corresponding error message.
formHelperTextPropsFormHelperTextProps
FormHelperTextProps to customise FormHelperText component for a field. Multiple fields can be configured using the ConfigProvider component.
customIds{ field, label, helperText, error }
Overrides the default field, label, helper text, and error IDs used for accessibility.

Source Code

View the full implementation of this component on GitHub.