course content

Course Content

Introduction to React

Event HandlingEvent Handling

Event handling in React components is crucial for defining the user interface's response to user interactions, such as clicking a button or submitting a form.

In usual HTML, we use the onclick attribute of the button element to specify a function that handles the click event. React is similar, except the attribute name is in camelCase: onClick.

In functional components, the functions that handle events are usually created as inline functions inside the component's function.

Following is a very simple example of event handling:

In the above code, handleClick is the inline function that sets the innerHTML of the button to Clicked! when it's clicked.

It is important to note that we can use an external function to handle events as well:

However, the common convention is to use inline functions due to some of their advantages and neatness. Since inline functions have a local scope, we don't have to worry about duplicate naming.

Apart from that, accessing component data from the inline functions is easier, especially while using hooks which we will explore in the later chapters.

We can also directly embed inline functions into expressions to make the code shorter:

We can also pass extra arguments to event handlers using the following method:


What kind of functions are most suitable for event handling in React while using function components?

Select the correct answer

Section 5.

Chapter 5