Search code examples
reactjsreact-final-form

React final form triggers handleSubmit after the initial render


I've got only Switch component in my react-final-form. It looks like this:

<Form
  onSubmit={onSubmit}
  initialValues={initialValues}
  render={({ handleSubmit }) => (
    <form onSubmit={handleSubmit}>
      <Field name="booleanValue" component={Switch} onChange={handleSubmit}/> //triggers when receives value
    </form>
   )
  }
/>

I want to trigger handleSubmit only after user changes, not at first render of the form.


Solution

  • <Field/> doesn't have an onChange prop like you are attempting. Something like this could work.

    import { OnChange } from 'react-final-form-listeners'
    
    ...
    
    <Form
      onSubmit={onSubmit}
      initialValues={initialValues}
      render={({ handleSubmit, form }) => (
        <form onSubmit={handleSubmit}>
          <Field name="booleanValue" component={Switch}/>
          <OnChange name="booleanValue">
            {(value, previousValue) => {
              form.submit()
            }}
          </OnChange>
        </form>
       )
      }
    />
    

    P.S. I hope your Switch component knows to get its value and onChange from the input prop.

    Hope that helps!