7
votes

I'm trying to implement a form with two consecutive dependent Select with react-final-form and material-ui

sample form

Requirements

  • Both fields are required
  • When user selects a country value
    • city field should reset to blank
    • city field should not be marked as invalid
  • User should be able to reset the form completely anytime

I struggle to find a simple and elegant solution to this requirements with react-final-form API.

There may be approaches with mutators, react-final-form-listeners, or decorators but this seems to me like a common use case of forms for which a simple solution without advanced APIs would be nice.


Here is a version with a combination of FormSpy component, useRef hook and the form.reset api.

https://codesandbox.io/embed/react-final-form-material-ui-field-dependencies-hn7ps

  • subscribre to form values via FormSpy onChange prop
  • update a react ref each time values change
  • compare ref values with new values and use form.reset API to reset city field value without triggering validation

Here is another version using Declarating Form Rules approach via react-final-form-listeners like Erik adviced to do.

https://codesandbox.io/embed/react-final-form-material-ui-field-dependencies-ijxd0

It is a lot more simpler, as we dont need a react ref, and FormSpy.


Both solutions works almost perfectly except that the form.reset method redefines form initialValues under the hood, so that the RESET button do not reset form to the original initialValues anymore.

Is there a builtin way to hook in form state changes and compare old/new values ?

1

1 Answers

4
votes

Perhaps Declarative Form Rules are what you need?