Handling Events

Learn to implement logic when users interact with components using events.

JavaScript events are invoked when a user interacts with a web app. For example, when a user clicks a button, a click event will be raised from that button. We can implement a JavaScript function to execute some logic when the event is raised. This function is often referred to as an event listener.

Note: In JavaScript, event listeners are attached to an element using its addEventListener method and removed using its removeEventListener method.

React allows us to declaratively attach events in JSX using function props, without the need to use addEventListener and remove EventListener. In this section, we are going to implement a couple of event listeners in React.

Handling a button click event

In this section, we are going to implement an event listener on the “Ask a question” button in the HomePage component. Follow these steps to do so:

  1. Open HomePage.tsx and add a onclick event listener to the button element in the JSX:

Get hands-on with 1200+ tech skills courses.