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
value
andonChange
props.
2. Call RHF’s setValue
to onChange
prop so that RHF knows about value changes from the picker. It is important to use the 3rd argument to enable validation and isDirty
state update. fieldName
is a string representation of the property name the date picker is to hook up in our RHF schema.
3. 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.
4. 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 watch
is the perfect tool for this job. Note, the value coming from remote could be undefined
, we default it to null
here.
Update 25/04/2021: Watch
should not be used here because it will trigger re-render, getValues
should be used here instead.
Update 27/04/2021: No getValues
should be used in callback, it is always lacking behind render, so, I am back to watch
..
You may have noticed that in the above code, we have setDate
called in two places. Since the useEffect
will watch the value
changes and update the state with setDate
, we can safely delete setDate
in 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
: