Yomi Eluwande JavaScript Developer. Wannabe Designer and Chief Procrastinator at Selar.co and Worklogs.co

React onClick event handlers: A complete guide

4 min read 1281

React onClick Event Handlers: A Complete Guide

In this tutorial, we’ll go over the basics of React’s onClick event handler, including event listening, binding methods, and dealing with custom events.

What are event handlers in React?

Event handlers determine what action is to be taken whenever an event is fired. This could be a button click or a change in a text input.

Essentially, event handlers are what make it possible for users to interact with your React app.

Handling events with React elements is similar to handling events on DOM elements, with a few minor exceptions. If you’re familiar with how events work in standard HTML and JavaScript, it should be easy for you to learn how to handle events in React.

If you’re new to React or just need a quick refresher on handling events, this video tutorial breaks down the concept quite nicely.

What is the onClick handler in React?

The React onClick event handler enables you to call a function and trigger an action when a user clicks an element, such as a button, in your app.

Event names are formatted in camelCase, so the onclick event is written as onClick in a React app. In addition, React event handlers appear inside curly braces.

Take the following simple example written in HTML:

<button onclick="sayHello()">
  Say Hello
<button>

In a React app, this would be written as follows:

We made a custom demo for .
No really. Click here to check it out.

<button onClick={sayHello}>
  Say Hello
<button>

Another key difference is that, whereas you would simply return false to avoid default behavior in HTML, in React, you must explicitly call preventDefault.

The following example shows how to prevent a link from opening a new page by default:

<a href="#" onclick="console.log('The link was clicked.'); return false">
  Click me
</a>

You would write this as follows in React:

function ActionLink() {
  function handleClick(e) {
    e.preventDefault();
    console.log('The link was clicked.');
  }
  return (
    <a href="#" onClick={handleClick}>
      Click me
    </a>
  );
}

Synthetic events in React

React implements a synthetic events system that brings consistency and high performance to React apps and interfaces. It achieves consistency by normalizing events so that they have the same properties across different browsers and platforms.

A synthetic event is a cross-browser wrapper around the browser’s native event. It has the same interface as the browser’s native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers.

It achieves high performance by automatically using event delegation. In actuality, React doesn’t attach event handlers to the nodes themselves. Instead, a single event listener is attached to the root of the document. When an event is fired, React maps it to the appropriate component element.

Listening to events in React

To listen to events in React, add the onClick attribute, which is the event handler, to the target element. This specifies the function to be executed when that element is clicked. The onClick attribute is set to the showAlert function, which alerts a message.

This means that whenever the button is clicked, the showAlert function is called, which, in turn, shows the alert box.

Binding functions in React

In JavaScript, class methods are not bound by default. Therefore, it’s important that we bind functions to the class instance.

Binding in render()

One way to resolve the problem of binding is to call bind in a render function.

In the example above, we are using the onChange event handler to listen for typing events on a text input. This is done by binding it in the render() function. This method requires calling .bind(this) in the render()function.

Why?

Any ES6 class method is a plain JavaScript function; therefore, it inherits bind() from the Function method. So now when we call onChange() inside JSX, this will point to our class instance. Easy-peasy.

However, using this method means that there might be some performance implications since the function is reallocated on every render. This performance cost might not be visible at all in small React apps, but it could become noticeable in bigger React apps.

Binding in constructor()

If binding in the render doesn’t work for you, you can bind in the constructor. See an example below:

As you can see above, the changeText function is bound in the constructor.

js
this.changeText = this.changeText.bind(this)

Let’s go over how the line of code above works.

The first this.changeText refers to the changeText method. Since this is done in the constructor, this refers to the ChangeInput class component.

The second this.changeText is also referring to the same changeText() method, but we are now calling .bind() on it.

The final this is the context we are passing to .bind(), and it refers to the ChangeInput class component.

It’s also important to note that if changeText isn’t bound to the class instance, it won’t be able to access this.setState because this will be undefined. This is another important reason to bind event handling functions.

Binding with arrow functions

You can handle events is by binding with the fat arrow function.

ES7 class properties enable bindings at the method definition, as shown in the example below.

By definition, an arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target.

In the example above, once the component has been created, the this.handleEvent will never change again. That, in turn, means <button> won’t get re-rendered. This approach is very simple and easy to read.

This methods also has its performance costs, just like binding in the render function method.

Custom components and events in React

When it comes to events in React, only DOM elements are allowed to have event handlers. Take the example of a component called CustomButton with an onClick event. This wouldn’t respond to clicks because of the reason above.

So how do we handle event handling for custom components?

By rendering a DOM element inside the CustomButton component and passing the onClick prop into it. Our CustomButton is essentially a pass-through for the click event.

In the example above, the CustomButton component is passed a prop of onPress, which then gets passed into the onClick of the button.

Conclusion

Event handlers determine what action should be taken when an event occurs. The onClick event is used to listen for click events on DOM elements.

When it comes to event handling, binding is a very important topic, and there are several ways to go about it. So the question now is which of the binding methods do you use?

For most apps, the performance implications of binding in the render function won’t be noticeable, so you can consider using this method for readability and maintenance advantages.

But for superior performance, you should consider using the binding in the constructor method.

However, if you’re already writing Stage 2 JavaScript code, then using the arrow function is your safest best.

Monitor all onClick events in production

Debugging React applications can be difficult, especially when there is complex state. If you’re interested in monitoring and tracking Redux state for all of your users in production, try LogRocket.

LogRocket is like a DVR for web apps, recording literally everything that happens on your site. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred.

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

Modernize how you debug your React apps — .

Yomi Eluwande JavaScript Developer. Wannabe Designer and Chief Procrastinator at Selar.co and Worklogs.co

2 Replies to “React onClick event handlers: A complete guide”

Leave a Reply