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 returnstrue
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:
} label="Profil öffentlich (beinhaltet Vor- und Nachname)" />
This in turn is a fully working checkbox component:
} label="Steuerbescheinigung benötigt?" />
How to usereact-hook-form
in MUI switch and set initial value?
According todocumentation.
You need to wrap your
For example: You can see the complete exampleSwitch
component using theController
component fromreact-hook-form
and pass thevalue# from the field object ## and
onChangeproperties.
here.