class AddOption extends React.Component {
handleAddOption(e) {
e.preventDefault();
const option = e.target.elements.option.value.trim();
if (option) {
alert("handleAddOption");
}
}
render() {
return (
<div>
<form onSubmit={this.handleAddOption}>
<input type="text" name="option" />
<button>AddOption</button>
</form>
</div>
);
}
}
Form onSubmit
is a more correct approach, for the simple reason that a form can also be submitted with the ENTER key, and not just by clicking the submit button.
The name
attribute specifies the name of an element.
The name
attribute is used to reference elements in a JavaScript, or to reference form data after a form is submitted.
Note: Only form elements with a name
attribute will have their values passed when submitting a form.