简体   繁体   中英

React JS, two submit buttons in one form

When using React JS, how can I identify which button was used to submit the form?

I thought something like this would work, but it doesn't:

export default function App() {
  const onSubmit = e => {
    e.preventDefault();
    console.log(e.target.btn.value);
  };

  return (
    <form className="App" onSubmit={onSubmit}>
      <button type="submit" name="btn" value="wow">
        Button 1
      </button>
      <button type="submit" name="btn" value="oh no">
        Button 2
      </button>
    </form>
  );
}

Code sandbox

According to standard HTML you should be able to name two buttons the same name? Or use formaction attribute to distinguish them.

In my use case the buttons don't have knowledge about the form. I want to avoid a solution where I use some temporary state to remember which button was clicked.

In standard HTML you can do this:

<form action="/action_page.php">
  <input type="submit" name="btn" value="Submit">
  <input type="submit" name="btn" value="Submit2">
</form> 

When you submit the form btn will either be posted Submit or Submit2 depending on which button you click. I want to get as close as possible to this standard when building my React form. Use as little help from Javascript and React as possible. 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.

Try using event.submitter.name property. Add different name to your buttons and check their names in eventHandler . If you use some kind of library for making forms it may lay in e.nativeEvent.submitter.name
More info https://developer.mozilla.org/en-US/docs/Web/API/SubmitEvent/submitter

Either you can try the below code or you can try to make separate calls for both buttons.

Demo link codesandox

import React from "react";
import "./styles.css";

export default function App() {
  const state = {
    button: 1
  };

  const onSubmit = e => {
    e.preventDefault();
    if (state.button === 1) {
      console.log("Button 1 clicked!");
    }
    if (state.button === 2) {
      console.log("Button 2 clicked!");
    }
  };

  return (
    <form className="App" onSubmit={onSubmit}>
      <button
        onClick={() => (state.button = 1)}
        type="submit"
        name="btn1"
        value="wow"
      >
        Button 1
      </button>
      <button
        onClick={() => (state.button = 2)}
        type="submit"
        name="btn2"
        value="oh no"
      >
        Button 2
      </button>
    </form>
  );
}

You can determine which button was clicked by checking which element currently has focus using document.activeElement in the onSubmit function. Add different ids or data attributes to the buttons to determine which one was clicked.

Working with forms in ReactJS is rather straight forwards, if you know how input works. Here is some more information directly from the documentation: https://reactjs.org/docs/forms.html

And here is a small example which I will explain for you:

      // You need to add a onSubmit event to the form. This will trigger when you submit the for as you do any other html form (including pressing the submit button)
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          // need to save input value somewhere (use the state for this, check the link from above
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        // this is your button, as with other html forms.
        <input type="submit" value="Submit" />
      </form>

In the case you described, you shouldn't really submit the data inside the buttons (why would you do that?), but instead submit the form data inside inputs. If you really want two buttons for submit (although a form can be submitted by hitting the key enter for example), you can do so like this:

    // onSubmit is the same as before, handle form data here
    <form className="App" onSubmit={onSubmit}>
      // setSubmitButton would set the submit button to button1 (e.g. use react state for this)
      <button type="submit" onClick={setSubmitButton('button1')} name="btn" value="wow">
        Button 1
      </button>
      <button type="submit" onClick={setSubmitButton('button2')} name="btn" value="oh no">
        Button 2
      </button>
    </form>

As far as I understand from comments you want to have 2 submit buttons: one to "Save As Draft" another to "Submit".

I have this solution.

In DB for your post make a Boolean field "finished". If "finished" is "false" it's a draft, if "true" it's submitted.

Using React functional component in frontend set component state:

 const [finished, setFinished] = useState(false);

Then you have a form with "submitHandler" that saves it to DB and 2 submit buttons that set "finished" to true or false

 <form onSubmit={submitHandler}>
       //your other fields
       <button type="submit" onClick={() => setFinished(false)}">
         Save as a Draft
       </button>
       <button type="submit" onClick={() => setFinished(true)}>
         Submit
       </button>
    </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM