score:51

Accepted answer

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

score:23

The accepted answer is great and led me to my solution, but in case anyone comes here like I did looking for a way to modify field values from outside of the React application, you can do it by making a completely generic mutator that sets any field to any value, and getting a global reference to the bound mutator in the form like so

<Form
  mutators={{
    // expect (field, value) args from the mutator
    setValue: ([field, value], state, { changeValue }) => {
      changeValue(state, field, () => value)
    }
  }}
  render={({ form, ...rest }) => {
    // put the reference on a window variable of your choice here
    if (!window.setFormValue) window.setFormValue = form.mutators.setValue

    return (
      <>
        <Field name="field1">...</Field>
        <Field name="field2">...</Field>
        ...
      </>
    )
  }}
/>

// somewhere else, outside of the React application

window.setFormValue('field1', 'value1')
window.setFormValue('field2', 'value2')

The above is valid for v5.0.0 and up. In earlier versions the API was slightly different. Instead of using form.mutators, use the top level mutators prop for the render function i.e. render={({ mutators, ... }

Disclaimer: This pattern shouldn't be used unless absolutely necessary, for very particular usecases. For example, I'm using it for automating filling of fields from code which must be external to my React app. You shouldn't do this for actual application code. But if you do need to do it, it works great!


Related Query

More Query from same tag