Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-hook-form field value get lost when i collapse, add or delete panel

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

like image 604
Dhananjay Sharma Avatar asked Apr 23 '20 05:04

Dhananjay Sharma


People also ask

Is React hook form uncontrolled?

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 .

How do I add a default value in React hook form?

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' }) ).

How do you set the value of a select in React hook form?

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 .


1 Answers

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.

like image 95
shivam bhushan Avatar answered Oct 18 '22 17:10

shivam bhushan