Formik: Is there any way to pass a ref to the wrapped component to access the form externally?

Created on 21 Jul 2017  路  4Comments  路  Source: formium/formik

I'm looking for a way to trigger form submit call from outside/above the component returned from the Formik HOC, any idea would be appreciated.
Thanks

Most helpful comment

Thanks for your response.
Turns out the new submitForm method in v0.8.0 does exactly what I need. 馃帀


For context my use case was a little something like this:

Outside of Formik form

class WrapperComponent extends React.Component {
  state = {payload: null}

  onClick = () => {
    this.form.submitForm()
  }

  onSubmitCallback = payload => {
    this.setState({payload})
  }

  render () {
    return (
      <div>
        <FormikForm
          ref={node => (this.form = node)}
          onSubmitCallback={this.onSubmitCallback}
        />
        <button onClick={this.onClick}>submit</button>
        <pre>
          {JSON.stringify(this.state.paylaod, null, 2)}
        </pre>
      </div>
    )
  }
}

In Formik config

handleSubmit: (payload, {props, setSubmitting}) => {
  props.onSubmitCallback && props.onSubmitCallback(payload)
  setSubmitting(false)
}

All 4 comments

This is how I'm doing it: https://gist.github.com/mwickett/2aecfdeea40daa07d39e11922ae1fe20 (I _think_ this is kind of what you're referring too, but am not 100% sure. Apologies if I've misunderstood)

Thanks for your response.
Turns out the new submitForm method in v0.8.0 does exactly what I need. 馃帀


For context my use case was a little something like this:

Outside of Formik form

class WrapperComponent extends React.Component {
  state = {payload: null}

  onClick = () => {
    this.form.submitForm()
  }

  onSubmitCallback = payload => {
    this.setState({payload})
  }

  render () {
    return (
      <div>
        <FormikForm
          ref={node => (this.form = node)}
          onSubmitCallback={this.onSubmitCallback}
        />
        <button onClick={this.onClick}>submit</button>
        <pre>
          {JSON.stringify(this.state.paylaod, null, 2)}
        </pre>
      </div>
    )
  }
}

In Formik config

handleSubmit: (payload, {props, setSubmitting}) => {
  props.onSubmitCallback && props.onSubmitCallback(payload)
  setSubmitting(false)
}

@danhayden this is really useful. I think there should be a CodeSandbox.io for this snippet.
The tweak here being that the handleSubmit function actually receives the props as parameters.
Thanks for this!

Was this page helpful?
0 / 5 - 0 ratings