singingwolfboy
singingwolfboy

Reputation: 5556

How do I use multiple submit buttons with react-final-form?

I want to build a form using react-final-form that has multiple submit buttons, where each submit button sets a different value in the form. Essentially, I want to create a form that looks something like this in rendered HTML:

<form>
  Are you over 18 years old?
  <button type="submit">Yes</button>
  <button type="submit">No</button>
</form>

However, I can't figure out how to make react-final-form treat these different submit buttons as setting values in the form. I tried combining component state, <input type="hidden">, and onClick handlers, like this:

class FormWithMultipleSubmits extends React.Component {
  state = {
    value: undefined
  };

  setValue = value => this.setState({ value: value });

  render() {
    return (
      <Form>
        Are you over 18 years old?
        <Field
          name="adult"
          component="input"
          type="hidden"
          value={this.state.value}
        />
        <button type="submit" onClick={() => this.setValue(true)}>
          Yes
        </button>
        <button type="submit" onClick={() => this.setValue(false)}>
          No
        </button>
      </Form>
    );
  }
}

However, that doesn't seem to work -- probably because the value property on the <Field> component is only used for checkboxes and radio buttons.

Can someone give me a nudge in the right direction, for how to solve this properly?

Upvotes: 7

Views: 10088

Answers (1)

Erik R.
Erik R.

Reputation: 7272

Here's a Sandbox that shows how.

Upvotes: 15

Related Questions