0

I am trying to handle submitting a form in React. The form has two buttons which traditionally would send the form to two different locations using formaction. How can I get the formaction of the button the form is submitted in my onSubmit function in React?

onSubmit = (e) => {
    e.preventDefault();   
    if (formaction === 'download') {
        ...
    } else if (formaction === 'stop') {
        ...
    }
}

render() {
    return (
        <Form onSubmit={this.onSubmit}>
            ...
            <Button formAction="download" type="submit">Download</Button>
            <Button formAction="stop" type="submit">Stop</Button>
        </Form>
    );
)

2 Answers2

1

You could pass the onSubmit method to the button instead of form. And wire your name attribute to the formAction you like. In that way, you could access the formAction in e.target.name inside the onSubmit method.

 onSubmit = (e) => {
    e.preventDefault();   
    const formAction = e.target.name
    if (formaction === 'download') {
    } else if (formaction === 'stop') {
    }
}

render() {
    return (
        <form>
            <button name="download" type="submit" onClick={this.onSubmit}>Download</button>
            <button name="stop" type="submit" onClick={this.onSubmit}>Stop</button>
        </form>
    );
  }
Prateek Thapa
  • 4,366
  • 1
  • 8
  • 20
1

Ok, let's break it down. You are trying to use a combination of formAction attribute and onSubmit function.

FormAction attribute is basically used to override the default action attribute of the form. It defines URL to hit when a particular button of type submit is pressed. Hence, the value of formAction should be a URL. Have a look here

https://www.w3schools.com/tags/att_form_action.asp

Again coming to onSubmit function. The event target of the onSubmit function is the form element, so you won't be able to get any attribute of the actual button clicked, as you want right now.

To resolve the problem you can either move the onSubmit function to the individual button and handle the server call manually.

Or, you can have two different URL's for buttons and handle the logic on the server.

Also, I would recommend reading the order of events while form submission.

https://stackoverflow.com/a/29015329/2477472

cheekujha
  • 761
  • 4
  • 12