reactjsreact-final-formfinal-form

How to set/change Field value from external user action 🏁 React Final Form


There are many situations in which we might want to set the value of a specific field within a form to help out the user.

For example, an online fruit store may ask users how many apples they want to buy. To help users out, we could have 3 buttons such as

After going over what I thought were the two most relevant examples (Loading and Initializing Values and Calculated Fields), I still can't figure this one out without getting too hacky.

How can we set a field's value from a user's action (such as clicking a button)?


Solution

  • This can be accomplished by providing a mutators object to the Form component containing the necessary mutators, which will be made available to your component:

    <Form
      mutators={{
        setMin: (args, state, utils) => {
          utils.changeValue(state, 'apples', () => 1)
        },
        setMax: (args, state, utils) => {
          utils.changeValue(state, 'apples', () => 100)
        },
        setLast: (args, state, utils) => {
          utils.changeValue(state, 'apples', () => 6)
        },
      }}
      
      render={({ form, ...rest }) => (
        <>
          <button onClick={form.mutators.setMin}>minimum apples</button>
          <button onClick={form.mutators.setMax}>maximum apples</button>
          <button onClick={form.mutators.setLast}>what I bought last time</button>
        </>
      )}
    />
      
    

    As suggested by @davnicwil below, if you need to interact with the form from outside the React app (eg, you're using micro front-ends, you're migrating the app, or have some third party lib that lives outside React) you can save the form object (or any methods within) to the global scope using the render method, and call them as needed:

    render={({ form, ...rest }) => {
      window.form = form;
    
      // ... rest of code
    )}
    
    // later anywhere else in app
    window.form.mutators.setMax
    

    Erik's post