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

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 returnstruewith 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-formin MUI switch and set initial value?

P粉231112437
P粉231112437

reply all (1)
P粉933003350

According todocumentation.

You need to wrap yourSwitchcomponent using theControllercomponent fromreact-hook-formand pass thevalue# from the field object ## andonChangeproperties.

For example:

 ( } 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!