React Hook Form(RHF) has a Controller wrapper to help work with external controlled components like material-ui components. So far, I managed to use Controller wrapper element or useController hook to develop my forms without issues until material-ui/pickers. When I wrap KeyboardDatePicker, all functions work with one annoying warning:
Warning: A component is changing an uncontrolled input to be controlled
Inspired by the comment here, I figured out how to remove the above warning.
The idea is to manage a separate state for the date picker and manually wire it up RHF with useEffect.
- Setup a state and wire it up to 
valueandonChangeprops. - Call RHF's 
setValuetoonChangeprop so that RHF knows about the picker's value changes. It is important to use the 3rd argument to enable validation andisDirtystate update.fieldNameis a string representation of the property name the date picker is to hook up in our RHF schema. - Hook up the date picker with RHF by registering the field with 
useEffect. By now, the date picker would update RHF's model, and we can edit/save the date. However, when data arrives from the remote server and RHF form values are updated in our data initialisation process, the date picker is not updated. We deal with it next step. - To update the date picker when data initialisation happens, we need to watch the value changes coming from the RHF model and update the date picker. RHF's 
watchis the perfect tool for this job. Note, the value coming from the remote could be undefined. We default it to null here.You may have noticed that in the above code, we havesetDatecalled in two places. Since theuseEffectwill watch the value changes and update the state withsetDate, we can safely deletesetDatein our onChange prop. 
Final code:
Happy coding…
Update: 07/03/2021
For validation and general usage of the above date-picker, see below my own use case with Yup:
    
Top comments (0)