Access react-final-form values from outside the form

Viewed 2870

I have a react-final-form Form. The component exposes the values field. This field contains all the fields changed inside the form. The issue is, I want to access the values from outside of it.

     <Form onSubmit={onSubmit} render={({handleSubmit,values}) => 
       ...
       {JSON.stringify(values)} <- this works
     </Form>
<div>
{JSON.stringify(values)} <- this is outside, it doesn't work
</div>

I'd like to avoid shoving everything inside the form just to be able to access the values. Is there any way to access it outside or some way to at least pass a values/setValues from the outside to make the values visible outside the Form?

1 Answers

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:

  1. 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);
  1. 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;
  1. 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.

Related