Skip to Content
Piplup
@piplup/rhf-adaptersmui-materialComponents

MuiSwitchElement

Use MUI Switch with react-hook-form without writing a Controller. MuiSwitchElement binds the on/off state and validation to a form field.

Import

import { MuiSwitchElement } from '@piplup/rhf-adapters/mui-material';

Usage

'use client';import FormControlLabel from '@mui/material/FormControlLabel';import Stack from '@mui/material/Stack';import { MuiSwitchElement, MuiButtonElement } from '@piplup/rhf-adapters/mui-material';import { useForm } from 'react-hook-form';export default function Page() {  const { control, handleSubmit } = useForm({    defaultValues: { newsletter: false },  });  return (    <form onSubmit={handleSubmit((values) => alert(JSON.stringify(values, null, 2)))}>      <Stack direction="column" spacing={2}>        <FormControlLabel          control={<MuiSwitchElement control={control} name="newsletter" />}          label="Newsletter"        />        <div>          <MuiButtonElement control={control} type="submit" variant="contained">            Submit          </MuiButtonElement>        </div>      </Stack>    </form>  );}

Props

Prop

Type

MuiSwitchElement supports props of the MUI Switch component, along with additional adapter-specific props. For a complete list of available Switch properties, refer to the MUI API documentation.

The ref is forwarded to the underlying <Switch /> component.

useMuiSwitchAdapter

useMuiSwitchAdapter connects a field to React Hook Form and returns props you spread onto MUI's Switch. It's what MuiSwitchElement uses internally.

The element drops the error state and has no place for a message. Use the hook when a switch must show why it's invalid, like a required terms switch, or when the form should store something other than true/false.

Import

import { useMuiSwitchAdapter } from '@piplup/rhf-adapters/mui-material';

The terms switch must be on to submit. The newsletter switch stores "subscribed" or "unsubscribed" instead of a boolean.

'use client';import type * as React from 'react';import FormControlLabel from '@mui/material/FormControlLabel';import FormHelperText from '@mui/material/FormHelperText';import Stack from '@mui/material/Stack';import Switch from '@mui/material/Switch';import { MuiButtonElement, useMuiSwitchAdapter } from '@piplup/rhf-adapters/mui-material';import { useForm } from 'react-hook-form';import type { Control } from 'react-hook-form';type FormValues = {  newsletter: 'subscribed' | 'unsubscribed';  terms: boolean;};// A switch that must be on. `false` fails the `required` rule.function TermsSwitch({ control }: { control: Control<FormValues> }) {  const { error, helperText, ...adapter } = useMuiSwitchAdapter<boolean, FormValues, 'terms'>({    composeHelperText: true,    control,    messages: { required: 'You need to accept the terms to continue' },    name: 'terms',    required: true,  });  return (    <div>      <FormControlLabel control={<Switch {...adapter} />} label="I accept the terms of service" />      {error && <FormHelperText error>{helperText}</FormHelperText>}    </div>  );}// A switch that stores a string instead of a boolean.function NewsletterSwitch({ control }: { control: Control<FormValues> }) {  const { error, helperText, ...adapter } = useMuiSwitchAdapter<boolean, FormValues, 'newsletter'>({    control,    name: 'newsletter',    transform: {      input: (value) => value === 'subscribed',      output: (event: React.ChangeEvent<HTMLInputElement>) =>        event.target.checked ? 'subscribed' : 'unsubscribed',    },  });  return (    <FormControlLabel control={<Switch {...adapter} />} label="Send me the monthly newsletter" />  );}export default function Page() {  const { control, handleSubmit } = useForm<FormValues>({    defaultValues: { newsletter: 'unsubscribed', terms: false },  });  return (    <form onSubmit={handleSubmit((values) => alert(JSON.stringify(values, null, 2)))} noValidate>      <Stack direction="column" spacing={1}>        <TermsSwitch control={control} />        <NewsletterSwitch control={control} />        <div>          <MuiButtonElement control={control} type="submit" variant="contained">            Continue          </MuiButtonElement>        </div>      </Stack>    </form>  );}

How it works

Checked, not value. The hook returns checked instead of value. By default, checked is the field value converted to a boolean (!!value), and a toggle stores event.target.checked. So undefined, null, 0 and "" all show as off, and the form always stores a boolean after the first toggle.

Storing other values. transform.input maps the stored value to checked, and transform.output maps the change event to the stored value. Each replaces its default separately, so when the form stores anything other than a boolean, pass both. With only output, the default !!value still runs, and a stored "unsubscribed" shows as on because it's a non-empty string.

Required. required: true adds a rule with the message "Please fill out this field.", which you can change through messages.required. React Hook Form treats false as empty for required, so a boolean switch must be on to pass. With a transform that stores strings, both strings are non-empty and required never fails. Use rules.validate in that case, e.g. validate: (value) => value === "subscribed" || "Please subscribe".

The text rules (min, max, minLength, maxLength, pattern) are accepted but have nothing useful to check on a switch.

Errors and helper text. The result includes error and helperText, but Switch has neither prop. Take them out before spreading and render the message yourself, for example in a FormHelperText. With composeHelperText: true, helperText holds the error message while the field is invalid.

Generics. Without a transform, TypeScript can't infer the type of checked. Pass the generics explicitly: useMuiSwitchAdapter<boolean, FormValues, "terms">(...).

Props

Prop

Type

Return value

Prop

Type

See also

On this page