Back to: ReactJS Tutorials
Listening to Events and Working with Event Handlers in React with Examples:
In this article, I am going to discuss Listening to Events and Working with Event Handlers in React with Examples. Please read our previous article where we give you a brief introduction to State and Event in React.
Listening to Events and Working with Event Handlers in React:
This is our application at the moment, and it is fairly static. We have this output here on the screen, and we reached that output with the help of our components. But as we mentioned, this never changes, it’s static. We only have one state in this application, and that’s the initial state which we see here.
Now, let’s dive into how we can react to user events, and then we will have a look at how such events could trigger a state change.
How we can react to user events in React?
We want to start with events fairly simply. We want to start with clicks on a button to which we can react. And to get started with all of that, we will go to ExpenseItem, where we output the title, the amount, and so on. And there, we will also add a button below that div or right before we close the card component as shown in the below code.
<button>Change the Title</button>
And there, we just say “Change Title” inside the button tags. And if we now save that, we will see this button as shown in the below image.
Now the styling is not great, but this is just a temporary button. We will remove it later. We’re just using it here so that we can start diving into events and states. Later we’ll use what we learned in better places that help our application. But for a start, we now have these buttons, one per expense item component. And our goal now is simple. When this button is clicked, we want to change the title which is being output here.
Initially, the title which is being output is the title we get via props. But we will change it whenever this button is clicked. And therefore, we, first of all, need to find out how exactly we can react to button clicks in React. And it is very simple. On all built-in HTML elements, like divs and h2, and especially all the buttons and so on, we have full access to all these native DOM events which we can listen to.
So, if you search for an HTML button element, for example, or if you click on this link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button, you’ll find an article about this button. Scroll down the article, and you will see,
And there, if you click on the DOM Interface, HTMLButtonElement, you’ll see from which other elements or from whichever classes this inherits as shown below.
And here you’ll see that the HTML button element is a more specific form of the HTML element, which is a more specific form of the element, which is a more specific form of the node, and so on. And if we click on Element and then scroll down, for example, onClick Event Listener:
We will see that there are a bunch of events to which we can listen, for example, click and blur. And basically, for all these default events, there is a prop equivalent in React, which we can add to these built-in HTML elements to listen to these events. So instead of adding a listener as we would normally do it. For example, by selecting an element by ID and then adding an event listener like,
document.getElementById(‘root).addEventListener()
Which would be the imperative way of doing that.
What is onClick Event Listener and how it works?
In React, we add an event listener by going to the JSX element, like the button that we created. And there we add a special prop. But now it’s not a prop that sets some value for this button, but instead, it’s a prop that starts with ‘on’. Because react exposes all these default events as props that start with on.
And for example, here we can add onClick. Now, what does it do? it adds an event listener for clicking events to this button. Now we just need to define what should happen when such a click occurs. And we do that by assigning a value to this click event. And the value here has to be code that should be executed when that click occurs.
How do we define codes that should eventually be executed in programming?
Well, we create a function. So, all these event handler props, want a function as a value, a function passed as a value for onClick, and all these other on props which then are executed when that event occurs. Now, here, we can either create this function, for example, an anonymous arrow function. And then here we can console.log(‘Clicked!’),
<button onClick={() => {console.log(‘Clicked!’)}}>Change the Title</button>
And if we save that and we go back and open the developer tools in the browser, and there we go to the console part and if we click the button, we see click.
So, this is how that works. This is how simple it is to add an event listener to a React element. Now, typically, you don’t just want to work with such anonymous inline arrow functions though. By the way, it doesn’t have to be an arrow function. You can also create a function with the function keyword. You don’t want to overdo it at least. Because it would mean that you put a lot of code here into your JSX block, and that’s generally not a good idea. You should keep that lean and not put too much logic into your JSX code. Instead, you should define a function before the return block in the JSX code. And you can do that either with the function keyword or, again, by creating a const or a variable that holds an arrow function.
Calling a function when the button is Clicked:
So here we will add a clickHandler const, the name is up to you that holds an arrow function. And in there, we can do the same stuff that we do above. We can write a console.log as,
const clickHandler = () => {
console.log(‘Clicked!’);
};
After creating the arrow function, we pass the const name inside the onClick listener as shown above. And that’s important, we just point at it. We don’t execute it here. We don’t add parentheses here. Instead, we just repeat the name of the function. No matter if you created that function like this or with the function keyword, this does not matter. We just point at it. Why? Because if we add parentheses here, JavaScript will execute this when the button line of code is being parsed. And button line of code is being parsed when the JSX code is returned. So, it’s not executing clickHandler when the click occurs but when this JSX code is evaluated, and that would be too early.
That’s why we just point at the clickHandler. We pass a pointer at this function as a value to onClick, and then React basically memorizes this and executes the function for us whenever the click occurs so that it’s not executed when this is evaluated but when the click occurs, which is exactly what we want. So, if we save that and reload the page, you’ll see the same,
And that is how we can add event listeners to our elements. To all these built-in HTML elements, we can add supported event listeners. For example, OnClick is available on every element. Some events are only available on specific elements. But that is all based on the default DOM behavior. If an element supports an event, then you can add a listener with React by adding such an ‘on’ and then the event name prop.
Just make sure that the event name starts with a capital character, like in the case of onClick here. And then you just point at a function, either defined in line or, better, defined upfront, and React will execute that function for you when that event occurs.
That’s how you add events. Now, one word about naming these functions. It is a convention that you don’t have to follow but you might consider following that you name your functions like ‘clickHanlder’. If they are triggered upon an event, you end with the handler. This is not a must-do, and not every React developer does it, but it is a preference we personally have. And you will see it in a couple of projects out there.
so that it’s clear that this is a function that is not called by us, somewhere else in our code, but that it is a function that we attached to an event listener so that it’s eventually called by React when that event occurs. That’s why we’re naming our event handler functions like this, ending with the handler. But again, this is just our preference. Now with that, we know how we can react to events.
In the next article, I am going to discuss How Component Functions are Executed in React with Examples. Here, in this article, I try to explain Listening to Events and Working with Event Handlers in React with Examples. I hope you enjoy this Listening to Events and Working with Event Handlers in React with Examples article.