dohomi / react-hook-form-mui

Material-UI form components ready to use with react-hook-form
https://react-hook-form-material-ui.vercel.app
MIT License
562 stars 111 forks source link

If a form field is ever switched to required, it will always be required #299

Open EkaLinMan opened 3 months ago

EkaLinMan commented 3 months ago

Duplicates

Latest version

Current behavior 😯

Please check the demo, if the TextFieldElement or SelectElement is ever switched to required, it will always be required even if the required state is switched back to false.

Expected behavior 🤔

The required state of the form field should correspond to the real state passed from the required attribute.

EkaLinMan commented 3 months ago

We found a related issue in RHF, hoping it can help, thanks! https://github.com/react-hook-form/react-hook-form/issues/1749

EkaLinMan commented 2 months ago

We found the root cause, RHFM passes the empty object as the rule and leads to the issue, please check the demo, thanks! https://codesandbox.io/p/sandbox/broken-cookies-38y28p

image

sadik-malik commented 2 months ago

@EkaLinMan, use unregister when changing the isRequired property or anything in rules prop. React Hook Form will then re-register the component with the updated rules in next render.

EkaLinMan commented 2 months ago

@sadik-malik, thanks for your reply, we overrode the required rule to fix this issue, this way also works. {required: required ? "This field is required" : false}

But I'm afraid that the TextFieldElement is not the only one that has this issue. It would be great if RHFM could push a new version to fix all these issues in the future.

dohomi commented 1 month ago

@EkaLinMan could you elaborate why providing your own rules is not the solution for this problem? I use the rules object in all my project because I need translated versions of the required error message anyway, that might be the reason why this issue was never present in my projects. To rely on required prop only is just a "lazy" shortcut. I am happy to review a PR though to fix it in your favour.