Use material-ui/pickers with React Hook Form.
Rex
Posted on March 5, 2021
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. - Call RHF's
setValue
toonChange
prop so that RHF knows about the picker's value changes. It is important to use the 3rd argument to enable validation andisDirty
state update.fieldName
is 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
watch
is the perfect tool for this job. Note, the value coming from the remote could be undefined. We default it to null here.setDate
called in two places. Since theuseEffect
will watch the value changes and update the state withsetDate
, we can safely deletesetDate
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:
Posted on March 5, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 27, 2024