Reacts: Handling Events

Ifeoluwa Akinremi Wade
2 min readMay 30, 2022

--

Photo by Almas Salakhov on Unsplash

Brief Introduction To Events

What Are Events?

An event, in programming, is an identifiable action or occurrence.

What can trigger an event?
Usually an event is triggered by a user interaction, such as, a mouse click, or the pressing of a key on a keyboard.

Handling Events

My first experience with events in programming was with Javascript. The handling of a Javascript event looks like this:

function newProjectForm() {
let projectForm = document.getElementById("project-form")
projectForm.innerHTML +=
`
// html code for a form here
`
projectForm.addEventListener("submit", submitProjectForm)
}
function submitProjectForm(event) {
event.preventDefault()

// code for cool stuff to happen
}

Above is some code used to build a form and handle the submission of the user input. As you can see, an event listener is attached onto the form: projectForm.addEventListener("submit", submitProjectForm). The event that it will be listening for is "submit". Once the event is trggered, it calls the submitProjectForm method to handle the event, and what should happen when the event takes place. The event is passed into submitProjectForm, and the default action is prevented with event.preventDefault(), which would be submitting the form. Here is where the code will be that executes what will happen with the user input from the form.

Handling Events With React

Handling events with React, in comparison to Javascript, is very simple and straightforward. React tends to do a lot of the heavy lifting. Here is what submitting user input through a form:

handleOnChange = (event) => {  
this.setState({[event.target.name]: event.target.value})
}
handleOnSubmit = (event) => {
event.preventDefault();
// code for cool stuff to happen
}
render() {
return (
<div>
<form onSubmit={this.handleOnSubmit} id="form">
<br />
<h4>New Student Form</h4>
<label><u>Name</u>: </label>
<input id="form-input" type="text" name="name" onChange=. {this.handleOnChange} value={this.state.name} placeholder="First name, last name..." required />
<input id="form-submit" type="submit" value="Submit"/>
</form>
</div>
)
}

In React the handling of events is done by event handlers. Above there are two callback functions: handleOnChange, handleOnSubmit. These events are triggered by the event handlers: onChange (detects the change in the input) and onSubmit (form submission event). Because React is a Javascript framework, event.preventDefault() is used in the callback to prevent the default action of form submission.

--

--

Ifeoluwa Akinremi Wade
Ifeoluwa Akinremi Wade

No responses yet