Handling Events in React

Pranchal Agrahari
Last Updated: May 13, 2022

Introduction

The event handler determines what to do whenever an event is triggered. The event could be a  button click, a keyboard keypress, or a hovering mouse cursor.

Handling events in react is very crucial because changes made on event helps the user to interact with our application.

Handling events in react is very much similar to how we handle events in DOM elements. If you are familiar with handling events in javascript, then handling events in react would be a cakewalk for you.

But before starting with handling events in react, let,s first understand what is an event. 

React Events

An event is an action that is fired as a result of user actions or the action taken by the system. For example, clicking a mouse button, loading a web page, pressing a key, window resizing, and other interactions are called events.

React has its own system for handling events which is quite similar to how we handle events in DOM elements.

Now we will look at important rules to follow while creating events in React.

  • camelCase Convention: Instead of using lowercase for naming, we use camelCase while giving names of the react events. That simply means we write ‘onClick’ instead of ‘onclick’.
     
  • Pass the event as a function: In React, we pass a function enclosed by curly brackets as the event listener or event handler, unlike HTML, where we pass the event handler or event listener as a string.
     
  • Prevent the default: Unlike javascript, returning false inside the JSX element does not prevent the default behavior in react. Instead, we have to call the ‘preventDefault’ method directly inside the event handler function
function fun(){
doSomething(e){
  e.preventDefault();
  // Some more response to the event
}
return (
  <button onEvent={doSomething}></button>
);
}

 

Here, e is a synthetic event. React defines these synthetic events according to the W3C spec. A synthetic event is an object made with a wrapper around the actual event of the browser. This object is cross-browser.

Let’s implement a program for event handling in react for our better understanding .we will discuss the program from scratch and in-depth to better understand handling events.

Handling events in react

To create the program for handling event in react, we will firstly create a react application. We will create an app using create-react-app. If you want to learn how to create a react app, you can read out this article.

Steps to create the react app:

  1. Create the app using the following command on your command line:
npx create-react-app event_handling

 

2.  Now after creating the app change the working directory to folder of your project using the following command.

cd event_handling

  1.  

Now we have successfully created the app now we can start working on the app.

You will see the following folder structure 

In your index.js file write the following code to create a onclick event handler that gives an alert on button click.

import React from 'react';

import ReactDom from 'react-dom';

 

function App() {

  function eventHandler(){

    alert('Welcome to Coding Ninjas');

  }

 

  return (

    <div className='App'>

      <h1>Welcome to Coding Ninjas</h1>

      <button onClick={eventHandler}>Click me</button>

    </div>

  );

}

 

ReactDom.render(<App />document.getElementById('root'));

 

 

Output for the above code is :

Once you click on the button the alert is displayed

So we successfully created an app to handle events in react and also learned about event handling in detail with syntax.But what will happen if we are using a class component.

Let’s discuss event handling in class components in detail.

Handling events in class component

Handling events in class components is similar to handling events in functional components.

  1. Let's create an onclick event handler as we created above to understand it better.

import React from 'react';

import ReactDom from 'react-dom';

 

class App extends React.Component {

  eventHandler = () => {

    alert('Welcome to Coding Ninjas');

  };

 render() {

    return (

   

      <div className='App'>

      <h1>Welcome to Coding Ninjas</h1>

      <button onClick={this.eventHandler}>Click me</button>

    </div> 

    );

  }

}

ReactDom.render(<App />document.getElementById('root'));

 

 

If you have noticed we are using this keyword in the above keyword while calling the function this is because in  JavaScript, class methods are not bound by default. If you forget to bind this.eventHandler and pass it to onClick, this will be undefined when the function is actually called

2. In the above example we declared the function outside the render but we can also declare it directly in the onclick attribute like this

import React from 'react';

import ReactDom from 'react-dom';

class App extends React.Component {

 render() {

    return (

   

      <div className='App'>

      <h1>Welcome to Coding Ninjas</h1>

      <button onClick={()=>alert('Welcome to Coding Ninjas')}>Click me</button>

    </div>

    );

  }

}

 

ReactDom.render(<App />document.getElementById('root'));

 

 

Passing Arguments to Event Handler

Let’s say that you want to customize the message displayed on clicking the button , you want to display the name of the user. You want to change it for every user so you need a way to pass arguments to event handlers.

React allows us to pass arguments in the event handler. So let’s take a look at how you would pass arguments while handling events in react.

import React from 'react';

import ReactDom from 'react-dom';

 

function App() {

  function eventHandler(name){

    alert(`Welcome to Coding Ninjas, ${name}`);

  }

 

  return (

    <div className='App'>

      <h1>Welcome to Coding Ninjas</h1>

      <button onClick={()=>eventHandler("jhon")}>Click me</button>

    </div>

  );

}

 

ReactDom.render(<App />document.getElementById('root'));

 

 

 

3. In the case of class component we need to bind event handler with this so our code will become

import React from 'react';

import ReactDom from 'react-dom';

 

class App extends React.Component {

  eventHandler = (name=> {

    alert(`Welcome to Coding Ninjas,${name}`);

  };

 render() {

    return (

   

      <div className='App'>

      <h1>Welcome to Coding Ninjas</h1>

      <button onClick={()=>this.eventHandler("jhon")}>Click me</button>

    </div>

    );

  }

}

ReactDom.render(<App />document.getElementById('root'));

 

 Another way to bind the event handler is like this

<button onClick={this.eventHandler.bind(this"John")}>

 

 

In the above code the alert would be displayed with the name that is passed as an argument to the event handler.

Frequently asked questions

  1. What are the events in react?
    An event is an action that is fired as a result of user actions or the action taken by the system. For example, clicking the mouse button, loading of a web page, pressing a key, window resizing, and other interactions are called events.
     
  2. What is an onClick() event?
    onClick() event occurs when a user clicks on something. It helps the developer to execute a piece of code when a user clicks on the specified objects.
     
  3. How to pass arguments to an event in react?
    There are two ways to pass arguments via the Arrow function and the Bind method.

    Arrow Function
<button onClick = {(e)} => this.handleClick(id,e)>Delete</button>

 

    Bind Method

<button onClick={this.handleClick.bind(this,id)>Delete</button>

 

Key Takeaways

This blog covered the basic concepts of handling events with React, creating the application for handling events and discussed the syntax and program in detail.

If you are preparing for the next interview, check out the blogs 15 Most Frequently Asked React JS Interview Questions and 10 Best ReactJS Interview Questions. And if you are a beginner, check out the Top 5 skills to learn before you start with ReactJs to know the prerequisites to learn React.

If you are preparing for your DSA interviews then, Codestudio is a one-stop destination. This platform will help you acquire effective coding techniques and give you an overview of student interview experience in various product-based companies.

 

 

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think