When using React JS, how to 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>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With