I am using material ui ExpansionPanel. I am trying to add new panels from Add button click and remove panel from Remove button click, its working fine, problem is, when i expand, collapse, add or remove panels, form fields value get lost. I think it happens due to re-rendering or refresh.
Let me know how can we implement above feature so that user can easly navigate to any panel add some detail from there and move to another panel and add some detail there, but while adding details from one to another panel, value must be there if user again goes to that perticular panel.
Have a look on below sample code
https://codesandbox.io/s/dhananajayx-3n73x?file=/src/App.js:146-160
Any effort is highly appreciated
React Hook Form relies on uncontrolled form, which is the reason why the register function capture ref and controlled component has its re-rendering scope with Controller or useController .
The solution is to use the reset() function from the React Hook Form library, if you execute the function without any parameters ( reset() ) the form is reset to its default values, if you pass an object to the function it will set the form with the values from the object (e.g. reset({ firstName: 'Bob' }) ).
you can use a useState() to control the default value that you fetch with the getData() method and then pass the state to defaultValue param in the Controller .
useForm({ shouldUnregister: false });
When working with react-hook-form and each form element is rendered on a tab change or so, use the above code to not let any field unregister from the form and keep the form values as it is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With