The onClick handler in React enables you to call a function and performs an action when an element is clicked in your app. It is the cornerstone of any React app. Before discussing the onClick event in ReactJs, first, let us understand what event handlers are. 

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Event Handlers

Generally, in JavaScript, event handlers are used to determine which action is needed after firing the action, such as clicking any button or changing with text input. The users can interact with our ReactJS application through the event handlers.

If you already know how to handle events in HTML and JavaScript, handling events in ReactJS becomes easy. Like how we handle events within our DOM elements, we can handle the events in ReactJs elements, barring exceptions.

Now let us appropriately discuss the onClick event handler in ReactJs.

onClick Event Handler in ReactJs

Whenever the user clicks a button or any element within our application, the onClick event calls a function, and the called function triggers an action. The event handlers in React always appear within the curly braces.

Now let us see some examples. 

Example: 

1. In HTML:

<button onclick="newEvent()">

  Hello World!

<button></button>

2. In React Application:

<button onClick={newEvent}>

  Hello World!

<button></button>

There is an important difference between using onClick in React and onClick in HTML. To avoid the default behavior in HTML, we simply return false, but in ReactJS, the preventDefault method needs to be called explicitly.

Now let us see an example code implementation for avoiding the opening of a page from a link by default in HTML:

<a href="#" onclick="console.log('The link has been clicked.'); return false">

  Click this link

</a>

Now, let us see how we can do this in React Application:

function ActionLink() {

    function handleClick(e) {

      e.preventDefault();

      console.log('The link has been  clicked.');

    }

    return (

      <a href="#" onClick={handleClick}>

        Click this link

      </a>

    );

  }

The onClick is an event handler for the target element within our React application. Generally, this event handler specifies which function must be executed after that particular element is called. We add the onClick event handler to the elements as the attributes.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Now we will see an example where a function will be set to the onClick event of a button; as soon as the button is clicked, the onClick event will execute the function, and the function will run, giving us the expected output.

import React, { Component } from "react";

import ReactDOM from "react-dom";

class GreetAlert extends Component {

  greetAlert() {

    alert("Welcome to the world of Programming!");

  }

  render() {

    return <button onClick={this.greetAlert}>Click to view the alert!</button>;

  }

}

export default GreetAlert;

In the above code, we can see a function called GreetAlert() which we had defined earlier, and then we pass the function within the onClick attribute of a button element in our react application. Whenever the user clicks the “Click to view the alert!” button, there will be an alert popup on the top of the screen.

There are some events in React called synthetic events. Let us discuss this topic in brief.

Synthetic Events in React

The synthetic events provide high performance and consistency to the React application or its interface.

The synthetic events achieve consistency by normalizing the events to get the same properties across the different browsers or platforms. It is a cross-browser wrapper around the browser’s native event. Except for those events which work uniformly across all the browsers, including the preventDefault() and stopPropagation(), as the browser’s native event, it has the same properties. High performance is achieved automatically by these synthetic events by using delegation.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Handling Events in Class Components

In the class components, the events can be handled by binding them within the arrow functions. Binding in the method function is allowed in the ES7 class properties.

Binding With Arrow Functions

The arrow function does not have its own properties like arguments, this, super, and new.target. An arrow function’s syntax is shorter than the normal function’s syntax.

Let us see an example of code implementation of arrow functions:

import React, { Component } from "react";

import ReactDOM from "react-dom";

class AlertInput extends Component {

  eventHandlingAlert = event => {

    alert("I have been clicked");

  };

  render() {

    return (

      <button onClick={this.eventHandlingAlert}>Click to view the aler1!</button>

    );

  }

}

export default AlertInput;

Now we are going to discuss some ways of handling events within the functional components:

Handling Events in Functional Components

  • Using an Inline Function

In ReactJs, we can write the event handling code within the JSX directly and it is mainly enabled by the inline function. We just need to pass the inline function to the onClick event handler. Sometimes these inline functions are not readable if the code content for the inline function is too much. These inline functions are mainly used to avoid the declaration of the function outside the JSX.

Now let us understand how to use the inline function within a function component through an example:

Example:

import React from "react";

const App = () => {

  return (

    <>

      <button onClick={() => alert("Welcome to the world of Programming!")}>Greetings Button</button>

    </>

  );

};

export default App;

  • Updating Local States

Sometimes in our React application, we need to update our local states; this updating process of the states can be done within the onClick event handler.                                                                                       

Example:

Say for instance your React application requires you to update the local state in an onClick event handler.

Here, within our react application, we have a local state called count whose initial value is set to 0 and two buttons, increment and decrement, within our component. With the two buttons (one button will be for incrementing the count value and another button will be for decrementing the count value), we can modify and update the value of the local state using setCount() as shown below.

import React, { useState } from "react";

const App = () => {

  const [count, setCount] = useState(0);

  return (

    <>

      <p>{count}</p>

      <button onClick={() => setCount(count + 1)}>Increment Button</button>

      <button onClick={() => setCount(count - 1)}>Decrement Button</button>

    </>

  );

};

export default App;

  • Call Multiple Functions 

Within the same onClick event handler, we can pass multiple functions.

Now lets see an an example where we will call two functions within the same onClick event handler. 

Example: 

As shown in the code below, one function is for displayinng the greet alert and another one is for updating the local count state in our React application.

import React, { useState } from "react";

const App = () => {

  const [count, setCount] = useState(0);

  const greetAlert = () => {

    alert("Welcome to the world of programming!");

  };

  return (

    <>

      <p>{count}</p>

      <button

        onClick={() => {

          greetAlert();

          setCount(count + 1);

        }}

      >

        Multiple function executing button

      </button>

    </>

  );

};

export default App;

  • Pass a Parameter

We can pass the parameters to the event handlers, and use those parameters later. 

Example:

In the sample code below, we have a function called greetAlert which accepts a name parameter, and that parameter is used to show the name in the alert output.

import React from "react";

const App = () => {

  const greetAlert = (name) => {

    alert(`Say hello to , ${name}!`);

  };

  return (

    <button

      onClick={() => {

        greetAlert("Mosh");

      }}

    >

     Greet Button

    </button>

  );

};

export default App;

  • Use Synthetic Events Directly Inside onClick Event

Inside the onClick event, the synthetic events can be used directly. 

Example:

In the example below, we will get the button’s values through e.target.value:

import React from "react";

const App = () => {

  return (

    <button value="Welcome to the world of programming!" onClick={(e) => alert(e.target.value)}>

      Greeting button

    </button>

  );

};

export default App;

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Event Handling for Custom Components

In ReactJS, only the DOM elements can have event handlers. If the event handlers are passed to components like NewCustomButton, we will get no response. What do we do in such situations? Here’s the solution.

First, in the NewCustomButton component, we need to render the DOM element, and then the onClick prop will be passed to it.

Let us see the code implementation for this:

import React from "react";

const NewCustomButton = ({ onPress }) => {

  return (

    <button type="button" onClick={onPress}>

      Click on me

    </button>

  );

};

 

const App = () => {

  const handleEvent = () => {

    alert("I have been clicked");

  };

  return <NewCustomButton onPress={handleEvent} />;

};

export default App;

Conclusion

In this article, we discussed that the onClick event handler plays a very important role in ReactJS. These event handlers are used to determine which action needs to be triggered after clicking the DOM elements in which the onClicker event handlers have been passed. In class components, event handling can be done through binding. We can also use the onClick events in function components in different ways discussed earlier in this article.

Today, in this time and age, along with data structure and algorithms, your development skill is equally crucial to making a mark in the tech industry. Therefore, a tech professional should always keep himself updated with the latest technology and software in the field of Web Development. 

Simplilearn offers some excellent Full Stack Web Development Certificate Courses that you can check out. These courses are designed to help you master both the front-end and back-end with different technologies and tools like AngularMVC and SpringBoot.

If you are looking for short-term courses to upgrade your skill set, Simplilearn also offers free online skill-up courses in domains like data science, business analytics, software development, AI, and machine learning. 

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 17 Jun, 2024

6 Months$ 8,000
Full Stack Developer - MERN Stack

Cohort Starts: 24 Apr, 2024

6 Months$ 1,449
Automation Test Engineer

Cohort Starts: 1 May, 2024

11 Months$ 1,499
Full Stack Java Developer

Cohort Starts: 14 May, 2024

6 Months$ 1,449