I'm trying to implement a form with two consecutive dependent Select with react-final-form and material-ui
Requirements
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
onChange
propform.reset
API to reset city field value without triggering validationHere 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 ?
You can use the form values from the render props of final-form. import { useFormState } from 'react-final-form'; const ChildComponentOfForm = () => { const { values } = useFormState(); const value = values['field-name']; ... }
Good news! React Final Form was written by the same guy (@erikras) that wrote Redux Form, so much of the API is exactly the same.
The variable pristine sets the disable prop to true only when the form loads for first time, but when the user submit the form (not reloading the page) the variable pristine is false and I expect it to be true in order to disable the "Submit" button. The Submit button is disabled when the form loads for first time.
React Final Form is a thin React wrapper for Final Form, which is a subscriptions-based form state management library that uses the Observer pattern, so only the components that need updating are re-rendered as the form's state changes.
Perhaps Declarative Form Rules are what you need?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With