ReactJS Handling Events

Learn via video courses
Topics Covered

Overview

In essence, event handling in React enables a user to interact with a webpage and take specified action whenever an event, like a click or a hover, takes place. Events in React are fired when a user interacts with an application, such as mouseovers, key presses, change events, and so on. The application must run the code and handle events. Events are essentially the actions that javascript can react to.

Introduction

The system can start many different events, like clicking, page loading, key presses, scrolling, etc. React offers event management that is comparable to DOM element event handling. React events are synthetic events that cover the native event of the browser across all supported browsers. In every browser, it operates the same.

Any time a user clicks on an object puts text into an input box, drags or drops an element, and so on, events often reflect some form of interaction between the user and the app. As a result, the app typically needs to respond to each event in some way. As programmers, we can construct a function that is used to react to a critical event whenever it occurs. Every programming language's heart of event management is a set of operations known as event handlers. A collection of methods are used to manage events in React.

The same applies to react! We'll be delving more deeply into the idea of event management in React in this guide. We'll examine a variety of event kinds as well as the handling techniques employed in each case.

Introduction to event handling in react

Events are the things that javascript can react to. Event handling in React is quite similar to DOM element event handling. The following are some specific events in React that you could encounter when interacting with websites built with React:

  • Clicking an element
  • Submitting a form
  • Scrolling page
  • Hovering an element
  • Loading a webpage
  • Input field change
  • User stroking a key
  • Image loading

Difference Between Html And React Event Handling

With a few syntax modifications, React event handling is identical to HTML. For example:

  1. React uses camelCase for event names, while HTML uses lowercase.
  2. Instead of passing a string as an event handler, we pass a function in React.

Example

In HTML

In React js

Additionally, much like in HTML, we cannot return false to override default behavior; instead, we must use preventDefault.

In HTML

In React.js

Here OnClick event listener changing state and hence this needs to be called. To update the state value, use the onClick handler's setState method (for class components) or useState hook (for functional components). The given example demonstrates how the class component is used to implement it.

Refer to the following example if you want to do the same thing with a functional component.

We cannot return false in react to override the default behavior. To stop the default behavior, we must explicitly invoke the preventDefault event. For example:

In basic HTML, we may write the following to stop links from launching a new page by default:

In React, we can write it as:

In the example above, e is a Synthetic Event that is defined in accordance with W3C specifications.

Let's now examine how React uses events.

Example of How to Use Event in React

The term binding refers to mapping an event, an HTML element, and a javascript function. Events in React are typically used in conjunction with functions, and the function is not run until the event occurs.

The generic syntax is

Create a button element, and the function, func(), given below, will control what occurs when the onClick event is triggered.

Let’s see some of the event attributes:

  • onmouseover : The mouse is moved over an element
  • onmouseup : The mouse button is released
  • onmouseout : The mouse is moved off an element
  • onmousemove: The mouse is moved
  • Onmousedown: mouse button is pressed
  • onload : A image is done loading
  • onunload: Exiting the page
  • blur : Losing Focus on the element
  • onchange : Content of a field changes
  • onclick: Clicking an object
  • ondblclick: double clicking an object
  • onfocus: element getting a focus
  • Onkeydown: pushing a keyboard key
  • Onkeyup: keyboard key is released
  • Onkeypress: keyboard key is pressed
  • Onselect: the text is selected

These are some examples of events:

Synthetic Event:

When you specify an event in JSX, you deal with a form of event in React called a synthetic event rather than a conventional DOM event. It's just a straightforward wrapper for native event instances, and each synthetic event created necessitates garbage collection, which can be CPU-intensive. The following characteristics apply to the synthetic event object:

  • Boolean isTrusted
  • DOMEvent nativeEvent
  • number timeStamp
  • void preventDefault()
  • number eventPhase

Synthetic events in React offer an interface, minimize browser incompatibilities, and contain the necessary data for propagation. Synthetic events are cross-browser wrappers for native browser events that are reused for performance reasons. Synthetic events have the same interface as native events. The document node receives delegation for synthetic events. As a result, native events are triggered first, and as they document, synthetic events are then triggered. Performance-related considerations dictate that when the event callback has been triggered, the synthetic event object will be reused and all of its properties invalidated.

The workflow of the synthetic event in React is as follows:

synthetic event in React

The Basics of React Event Handling

Let's look into event handling in React and see how the click event applies to other kinds of events in React. By naming a file clickAppHandler.js, let's begin with the functional components.

Let's develop a functional component in this file as shown below.

As illustrated below, the clickHandler function is called when the onClick event occurs, and the console prints the word clicked when the button is clicked.

A component must then be added to the app component after this. You can see in the code above that when the button is clicked, the function is passed as the event handler. You will notice that we haven't added parentheses as it becomes a function, and we do not want that we want the handler to be a function not a function call. When a new component is rendered its event handler functions are added to the mapping maintained by the react. When the event is triggered and it hits and DOM object, react maps the event to the handler, if it matches it calls the handler

The event handling in react is declarative, and the advantage of the declarative way to handlers is that they are part of the User interface structure. Let’s take a look at event handling in class components

Some event handlers can be attached to an eventual parent of an element, and any events generated on that element will propagate to the parent as long as stopPropagation isn't used to stop it along the way, much like with the usual DOM API.

The event handlers that were activated in the bubbling phase are listed below:

  • MouseEvents

    • onClick
    • onDrag
    • onDoubleClick
  • Keyboard Events

    • onKeyDown
    • onKeyPress
    • onKeyUp
  • Focus Events

    • onFocus
    • onBlur

In the example below, we've added an onChange event in React and just utilized one component. The changeText method, which returns the company name, will be called by this event.

Output

When you execute the above code, you will get the following output.

React Event Handling code output

After inputting the name in the textbox, the output will look like the screen below.

React Event Handling code output 2

Passing Arguments to Event Handler

There are two ways arguments are passed to the event handler

Arrow Function

Here, onClick is the event, e is the event object, id can be state or props or some data.

Bind Method

The event object is automatically passed in this scenario.

In both ways, e stands for the react event and is supplied as the second argument after the id. With an arrow function, this event e is explicitly passed, whereas, with a bind method, it is passed automatically.

The response event comes from React, and it is an object. You can pass the anonymous arrow function directly rather than writing a new function just to pass arguments, as demonstrated in the render function below:

Output

Click on the button TestApp Dummy.

Let’s see only how the bind method looks like in the render function.

Binding Event Handler

If you have used JavaScript before then you are familiar with the this keyword and how it works. The callback's this keyword will point to undefined if it is not bound to the event handler. This behavior is exclusive to JavaScript and has nothing to do with React. The event handler can be bound to the keyword this in one of the following five ways.

1. Binding Inside the Constructor

When utilizing the class component, we can bind the this keyword to the event handler in the function Object. The most typical approach to solving discussed issue is given below.

2. Binding by Passing the Arrow Function Inside the Event Listener

The event listener's function can employ the arrow function. We don't need to bind the this keyword in this situation. But this approach has limitations of its own.

3. Binding Directly When Passing the Function

Bind the this keyword directly when passing a function in the event listener.

4. Use Functional Component with Arrow Function

We don't need to bind the this keyword if we utilize the functional component and the arrow function. The example that follows the above statement is given below.

Conclusion

In this article, we have learned about:

  • Introduction to event handling in React.
  • Difference Between Html And React Event Handling with their examples like:
    • React uses camelCase for event names, while HTML uses lowercase.
    • Instead of passing a string as an event handler, we pass a function in React.
  • Different types of react events, their attributes, and the Synthetic event.
  • How to use events in React with its example.
  • Passing Argument to event Handler in 2 different ways:
    • using Arrow function
    • using the bind method
  • Binding Event Handler, which included:
    • Binding Inside The Constructor
    • Binding By Passing Arrow Function Inside The Event Listener
    • Binding Directly When Passing The Function
    • Use Functional Component With Arrow Function