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>
);
}
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.
onClick
for each button? You can have a separate handler for each, or pass an argument to a shared handler. – Autosuggestion