Table of Contents
Events are a fundamental part of web development. Events are required so that the application can respond to user interactions. Learning to handle events in React is very important to become a good react developer.
Events Refresher
JavaScript is an event-driven programming language. An event can be an action like button click, keypress, or form submit. An event is said to be triggered/fired when these actions by the user take place.
In web development, there are different types of events. Some of them are:
- click – Triggered when the user clicks an element.
- keydown – Triggered when a key from the keyboard is pressed.
- submit – Triggered when a form is submitted.
- mouseover – Triggered when a user hovers the mouse over an element.
- focus – Triggered when a form input is focused/becomes active.
- change – Triggered when a form input value is changed or altered.
Event Listeners
Event listeners are pieces of code that developers attach to an element. They detect whenever a particular event occurs and run the provided event handlers.
Event Handlers
These are functions/methods explicitly defined for handling an event. The compiler executes them when an event on a particular element occurs. It is used together with event listeners.
Synthetic Events in React
React implements its event handling system. It wraps a layer on top of native browser events. React terms it as “synthetic events.”
Different browsers handle events in slightly different ways. Synthetic events in React removes the cross-browser inconsistencies in handling events.
In vanilla JavaScript, you interact with real DOM events, but in React, you interact with this synthetic event. You do not have to worry about it, but it is good to know.
The React Events Syntax
To add events to react elements, we need two things:
- An event listener.
- An event handler.
Event Listener Attribute
To listen for events and detect them, we have to specify the event listener attribute on the React/JSX element. The general form of this attribute is:
on[EventName]
Always write event listener name in camelCase notation. Examples include onClick, onSubmit, onChange, etc.
Event handler
It’s a function/method that you, as a developer, pass as a value to the event listener attribute. It comes into action when the specified event on the element occurs.
The example below logs a message to the console with every click on the button.
The event listener and the event handler are solely for the JSX/react element.
You can define and use event handlers in two ways:
- Using a named function: You can use class methods, function references and pass them to the event listener attributes.
- Using an anonymous function: You can also define and use an anonymous function right in the code inline:
onClick = { () => { // your code } }
React Events in Class Components
To use events with class components, we need to follow two simple rules:
- First, define a method on the class to use as an event handler.
- Now, use that method with the required event listener attribute. Don’t forget to use the “this” keyword to access the class method.
MyComponent.js class MyComponent extends React.Component { /* define the handler method */ myHandler = () => { /* perform state updates, call an API, etc. */ console.log(‘do something…’); } render() { return ( <div> <h1>React Events</h1> {/* pass the event handler to onClick */} <button onClick={this.myHandler}> Click Me </button> </div> ) } } export default MyComponent;
Accessing “this” inside class methods/handlers
The this
property is essential to update state and access props. Inside a standard class method, it is usually undefined. There are two ways to solve this problem:
- Use arrow functions (highly recommended). It auto binds the
this
object to the function/method properly. - Bind
this
to the handler with the.bind()
method in the class constructor.
/* This example code should clear out the confusion */ class MyComponent extends React.Component { constructor() { // bind this to myHandler method this.myHandler = this.myHandler.bind(this) } myHandler() { // this is available now in this no-arrow function due to bind } otherHandler = () => { // this is always available in arrow functions (recommended) } }
React Events in Functional Components
To use react events with functional components, we need to follow a similar technique. The only difference from class components is that you don’t have to use the this
keyword to access functions/methods.
MyComponent.js const MyComponent = props => { /* define the handler function */ const myHandler = () => { /* perform state updates, call an api, etc. here */ console.log(‘do something…’); } return ( <div> /* pass it to the onClick listener */ <button onClick={ myHandler }> Click Me </button> </div> ) }
You can define the handler function anywhere in your code. However, defining it inside the component allows access to the props, state, and other features. For this reason, we define it inside the component.
The Event Object
Every event handler function receives one default argument. It is called the event object and has the presentation of e
or event
. This event object contains all the details of the event that was triggered.
It also provides a few useful methods and properties, which are:
1. e.preventDefault()
Use this method when you want to prevent any default behavior of the browser when running the event. For example, when submitting a form, it is the browser’s default behavior to reload the page. We can avoid that by calling e.preventDefault()
inside the onSubmit handler function.
2. e.target
This property returns the DOM element where the event occurred.
/* Example: A handler function using the event object */ handlerFunction(e) { // e contains all the details of this event e.preventDefault(); // It removes the default event-related browser behaviors. console.log(e.target); // e.target returns the DOM element. }
Summary
We have just looked into the ways to add events to a React application. Now you can experiment with different events on form elements and buttons.
Once you start using events in your React apps, your application will start to grow. You can start using different APIs to fetch some data or work with state and props.
Always follow proper coding structure and guidelines. It will avoid frustration and benefit you in the long run.