Now that we have our form ready, let's take the next logical step and figure out how to submit the data to our API.
The first thing we need to do is to add an onSubmit event handler to the form. The handler is specific to the registration form, and thus should be associated with RegistrationForm. The most obvious place to define it is as a class method. Update RegistrationForm to the following:
class RegistrationForm extends React.Component {
handleRegistration = (event) => {
event.preventDefault();
event.stopPropagation();
}
render() {
return (
<form onSubmit={this.handleRegistration}>
<Input label="Email" type="email" />
<Input label="Password" type="password" />
<Button title="Register" />
</form>
)
}
}
this.handleRegistration is triggered whenever the form is submitted (for example, when a user presses the Register button) and the event is passed in as its only parameter.
The default behavior for the form is to send an HTTP request to the URL specified in the action attribute of the form. Here, we are not specifying an action attribute because we want to handle the form differently. Thus, we are calling event.preventDefault() to stop the form from sending the request. We are also calling event.stopPropagation() to stop this event from capturing or bubbling; in other words, it prevents other event handlers from handling it.
Next, we need to figure out how to obtain the value of each input box, compose the request, and then send it to our API.