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

1

7

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?

Argufy answered 14/8, 2018 at 10:20 Comment(0)
T
15

Here's a Sandbox that shows how.

Timorous answered 16/8, 2018 at 7:50 Comment(1)
If I have validation on a form, how can I disable validation for just one of these buttons?Minuend

© 2022 - 2024 — McMap. All rights reserved.