Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 374
singingwolfboy Avatar asked Aug 14 '18 10:08

singingwolfboy


People also ask

How do you handle two submit buttons in React JS?

Basically just add the buttons to the DOM inside my form and collect the values from the event that I have access to inside of the submit handler. Why not use onClick for each button? You can have a separate handler for each, or pass an argument to a shared handler.

Can you have multiple submit buttons in a form?

yes, multiple submit buttons can include in the html form.

How do I have two submit buttons?

Let's learn the steps of performing multiple actions with multiple buttons in a single HTML form: Create a form with method 'post' and set the value of the action attribute to a default URL where you want to send the form data. Create the input fields inside the as per your concern. Create a button with type submit.

How do I add a submit button in React?

To submit a form using the Enter key in React: Add a button element with type set to submit . Add an onSubmit prop that points to a submit handler function. Every time the user presses Enter, the handle submit function will be invoked.


1 Answers

Here's a Sandbox that shows how.

like image 56
Erik R. Avatar answered Nov 16 '22 03:11

Erik R.