How to use React Hook Form 7 with MUI switch
P粉231112437
P粉231112437 2023-09-16 19:43:09
0
1
594

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粉231112437
P粉231112437

reply all(1)
P粉933003350

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!