-
I'm not able to have a working checkbox group with Material UI and react-hook-form v7. I've tried multiple approaches following the official documentation, code snippets and countless threads, but I cannot get the combination right. My use case reduced to the absolute minimum (without Material UI) is defined in the following Codesandbox link: https://codesandbox.io/s/friendly-austin-8s0ot?file=/src/App.tsx The following link works partially. It doesn't show the initial values and it needs a click to any checkbox to "wake the form up", but after that the form works as expected: https://codesandbox.io/s/quirky-mirzakhani-oxvwp?file=/src/App.tsx As a note, I've tried with and without Any help or hint would be greatly appreciated. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 10 replies
-
what's the issue here? I am not very clear on the problem. Does this link have the issue? what's the step to reproduce the problem? |
Beta Was this translation helpful? Give feedback.
-
In your example, the "First tag" is not checked because Material UI expects it should be set with prop "defaultChecked" or "checked". When clicking on the "First tag" checkbox at the first time, react-hook-form will remove the value "First tag" and update DOM element of the checkbox but because it's already "unchecked" therefore it remains the same state "unchecked", that's why when clicking "Submit", the value is empty array. With checkbox group use case, it would be recommended to use Controller component or useController hook because it provides the selected value array of checkboxes in order to set checked or unchecked state. Working sample: https://codesandbox.io/s/busy-rhodes-56z14?file=/src/App.tsx |
Beta Was this translation helpful? Give feedback.
-
@celtric @bluebill1049 can you extend the above codesandbox to work with array of objects. example: Available Tags as [{label: "First tag", taggingLabel: "Avialabletags: First tag"}, {label: "Second tag", taggingLabel: "Avialabletags: Second tag"}] |
Beta Was this translation helpful? Give feedback.
@celtric
In your example, the "First tag" is not checked because Material UI expects it should be set with prop "defaultChecked" or "checked".
When clicking on the "First tag" checkbox at the first time, react-hook-form will remove the value "First tag" and update DOM element of the checkbox but because it's already "unchecked" therefore it remains the same state "unchecked", that's why when clicking "Submit", the value is empty array.
With checkbox group use case, it would be recommended to use Controller component or useController hook because it provides the selected value array of checkboxes in order to set checked or unchecked state.
Working sample: https://codesandbox.io/s/busy-rhod…