How To Handle Events In React

How To Handle Events In React

React elements have properties that are based on the standard DOM events. React elements are able to fire all the same events as the usual DOM elements. They are named using camelCase so don’t forget to use this convention on React Elements. So if you want to use onclick, it will actually be onClick. This is quite similar to how instead of using class, you need to use className. React handles *a lot* of different types of events, but we’ll stick to the basics here.

Adding an onClick property

For example we can add the onClick property to a button to handle an event. It is set to the curly braces { } because in React, that is how we pass an expression.

Now what we can do is create a method above the render method but below the state object which can handle an event. The convention is to always start these types of methods with handle. So ours will be handleIncrement(). All we want at this point is some evidence that the button was clicked. So to start, here we go.

Also note on the button element we are now passing a reference to that function using this.handleIncrement. The method is not called, rather it is only passing a reference to it unlike what you would see in plain JavaScript. Ok fair enough let’s see it in action.

I know, impressive!

Updating The State

Ok the next goal is to change the value of the count property in the state object when the button is clicked. First though, we need to see the sometimes confusing nature of this in JavaScript. We want to access that count value, so we can try something like this.

Try to click the button now, and you will see an error.

Uncaught TypeError: Cannot read property ‘state’ of undefined

This will likely happen to you more than once! It can be frustrating too when you can’t figure out why this is happening.

Binding Event Handlers In React

To fix this, we need to look at how to bind events in React. In JavaScript, the context for this changes depending on how a function or method is called. There are a few rules to be aware of, but the short answer is sometimes we need to explicitly bind this using the bind() method. Let’s see how to do that.

Constructor and Super

This first way around this pesky Uncaught TypeError: Cannot read property ‘state’ of undefined error is to add a constructor to the class, along with a call to super(), and then use the bind() method like so.

Ah ha! Now we can access the value held in the count property of the state object.

Arrow Functions As An Alternative

The solution above using a constructor, super(), and bind() can get tedious. This needs to be done for every single event handler, so it ends up being a lot of repetitive code. Another solution for the this binding problems is to use arrow functions instead. We’ve updated the count to 5 as well so when we test we can see a new result. Here is how.

This is a nice solution since now, you don’t need to always add a new bind() in the constructor for each event handler. You simply assign an arrow function to a property on the class and this gets bound correctly.

Updating State

Now that we have this working well, we can work on updating state. A key point to remember when using React is to not modify the date directly. In other words, don’t try to do something like this.

setState to the rescue

To update the state in react, you can use the setState() method. This tells React that there has been an update to state, then React figures out what part of the DOM it needs to update – and does so. Some of the other popular MVVM frameworks do this step automatically, but in React, we do need to make use of the setState() method like this.

This works!

The setState() method explicitly tells React that the state of this component is going to change. Now, when the render() method eventually gets triggered, it returns a new React element with any updates that have been made. At this point, React compares the new vs the old virtual dom and figures out what is different. It then updates the Real DOM with only those changes needed, not the entire DOM tree. This is what makes the performance very fast. In fact you can see this in the browser if you open developer tools and just look at what is changing when state gets updated. Pretty cool!

How To Pass Event Arguments

The last thing we can look at in this tutorial is how to pass an event an argument. We want to trigger onClick with a parameter. This is a little tricky so we need a diagram.
react pass event arguments
In order to pass an argument to an event handler, we can use an inline arrow function. So instead of using this

We will now use this

In the diagram above, this is represented by the orange circle. Now notice that the inline arrow function is being passed an object as an argument. This argument is now available to the handleIncrement event handler. In fact in the body of that function we can alert out e.message and we in fact are seeing the value of “Its Friday!” appear on the screen.
react pass event argument example

Learn More

In Summary

When dealing with events for React elements, we can take a similar approach as when handling events on regular DOM elements. There are a couple of differences such as React events being named using camelCase, and you pass a function as the event handler, rather than a string. When using classes to define a component, a common pattern is for an event handler to be a method on the class like we did in this tutorial.