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?
According to documentation.
You need to wrap your
For example:Switch
component using theController
component fromreact-hook-form
and pass thevalue# from the field object ## and
onChangeproperties.
here.