Home  >  Q&A  >  body text

How to use React Hook Form 7 with MUI switch

When using react-hook-form with a MUI switch, the switch does not show the initial value when the page loads, even if the value is set to true. However, this appears to be a display issue, as submitting the form without touching the button returns true with the switch defined as a value of true. Additionally, clicking these buttons (shown as false) once will have no effect (they still stay on the left), and a second click will actually toggle them again.

Use hook to set initial value (applies to all other field types):

useEffect(() => {
  if (userProfile) {
    setValue('firstname', userProfile.firstname);
    setValue('lastname', userProfile.lastname);
    setValue('show_profile', userProfile.show_profile || false);
  }
}, [userProfile]);

The implementation of the switch is as follows:

<FormControlLabel
    control={<Switch {...register('show_profile')} />}
    label="Profil öffentlich (beinhaltet Vor- und Nachname)"
/>

This in turn is a fully working checkbox component:

<FormControlLabel
    control={
      <Checkbox
        {...register('steuerbescheinigung')}
        name="steuerbescheinigung"
      />
    }
    label="Steuerbescheinigung benötigt?"
  />

How to use react-hook-form in MUI switch and set initial value?

P粉231112437P粉231112437422 days ago593

reply all(1)I'll reply

  • P粉933003350

    P粉9330033502023-09-17 15:30:52

    According to documentation.

    You need to wrap your Switch component using the Controller component from react-hook-form and pass the value# from the field object ## and onChange properties.

    For example:

    <Controller
      name="show_profile"
      control={control}
      render={({ field: { onChange, value } }) => (
        <FormControlLabel
          control={<Switch checked={value} onChange={onChange} />}
          label="Profil öffentlich (beinhaltet Vor- und Nachname)"
        />
      )}
    />;

    You can see the complete example

    here.

    reply
    0
  • Cancelreply