The simplest way I found to get the form state outside the form is to use a MutableRefObject
to get a reference to the form instance that is available inside the form.
Steps to achieve this:
- Create a
MutableRefObject
(it is basically just a ref
object whose current
value can be changed)
const formRef: React.MutableRefObject<FormApi> = useRef(null);
If you have interfaces for the form, you can add the form interface like this to get typings for the properties we can access through this reference:
const formRef: React.MutableRefObject<FormApi<IForm, Partial<IForm>>> = useRef(null);
- Inside the
<Form>
, attach the form
instance to the MutableRefObject
we just created:
<Form onSubmit={onSubmitHandler}>
{({ handleSubmit, submitting, form, dirty }) => {
// form reference to access for outside
formRef.current = form;
- Now you can use
formRef
to access all properties described here in Final Form Docs - 'FormAPi' like this:
formRef.current.getFieldState();
formRef.current.change('fieldName',"value");
Explanation:
This method essentially creates a ref
object and attaches the form
instance to the object, and since it is a MutableRefObject
, it can be changed without causing a re-render.
Now, the entire form state as well as modifications to the form can be accessed and controlled from anywhere.
Redux
? You could, then, use the values anywhere you want, at any level. – Ulphi