How to Use React OnClick Event Handler?

Tuesday, February 04, 2025

HOW DID YOU GET TO THIS PAGE? 
Of course, you would have searched for something in the search engine and clicked on the relevant link. Each one of these actions you took is called an event. It includes clicking a button or moving the mouse to a specific element. 

The webpage then responds to that event with corresponding actions. For example, when you go to the service page of the React development company and then click on the “Contact Us” button. It will take you to its Contact page. Why? Because it’s programmed to do so in the event of clicking the “Contact Us” button. 

Events play a very crucial role in programming languages like JavaScript. It helps make your web pages more interactive and engaging. The events of your software applications are managed by event handlers. Specific events are assigned to every event handler. 

For example, clicking events in the React application are managed using the onClick event handler. This article is your guide on how to use React onClick event handler. But before getting started, it’s important to get some basic understanding. 

1. What are Event Handlers in React?

Event handlers in React are functions used to manage specific events, such as pressing any key on the keyboard or hovering your mouse over an element. An event handler is invoked whenever an event occurs. It helps provide information regarding events including their types, elements on which they occurred, and so on. 

This information is leveraged to give an appropriate response to the event. In short, event handlers enable user interaction within a React app.

2. React’s onClick Handler

The onClick event handler function is triggered whenever a click event occurs on any element of the React app. When the onClick event is activated, all the event information is passed to the event handler function. 

To use the onClick event handler in React, you have to define it first in line by either using the separate method on the component class or an arrow function. The event handler is then attached to the element using the onClick attribute.

3. Synthetic Events in React

Synthetic events in React are a way of representing the browser events across all major browsers.

Instead of triggering native browser events directly, React creates its own event system that wraps the native events, ensuring that they act the same way across various platforms. So, now that they have the same properties in all platforms and browsers, the React apps can easily achieve consistency. 

Because of the synthetic event system, events across all browsers work identically. It even has the same interface as the browser’s native event. Moreover, synthetic events automatically use event delegation, which helps maintain high performance.

4. Using onClick to Handle Events in Class Components

You can use arrow functions to bind methods in the class components. This helps you to handle events more effectively. In the ES7 class properties, binding is simplified. 

4.1 How to Bind Using Arrow Functions?

The syntax of the arrow function is shorter than the traditional function declarations. Because it doesn’t have any properties of its own such as new.target, super, this, and arguments. Execute the code given below to implement the arrow functions.

import React, { Component } from "react";
import ReactDOM from "react-dom";

class App extends Component {
  constructor(props) {
    super(props);
    // Initialize state
    this.state = {
      isLiked: false,
    };
  }

  // Arrow function to handle toggling like state
  handleToggleLike = () => {
    this.setState((prevState) => ({
      isLiked: !prevState.isLiked,
    }));
  };

  render() {
    const { isLiked } = this.state;

    return (
      

{isLiked ? "You liked this!" : "You haven't liked this yet."}

); } } export default App;

5. Using onClick to Handle Events in Functional Components

The event handlers are triggered upon the occurrence of the given event. Event handlers in React are similar to the ones in JavaScript and HTML. Many event handlers are available in HTML including onFocus, onChange, and onClick. You can use these handlers by adding them to the HTML elements.


It’s the same case with React as well. The names of the event handlers are the same in HTML and React, only difference is they are written in camelCase. Therefore, the handlers have to translate it into onClick, onFocus, and onChange in React. 


If you examine the code carefully, you will know that the code isn’t the same as the HTML example we saw above. The double quotes are replaced with the curly braces that are used in JSX syntax to separate the markup from JavaScript. Therefore, everything inside the braces is considered JavaScript, and everything on the outside is considered markup. 

The code of your complete component will look as shown below:

import React, { useState } from "react";
import ReactDOM from "react-dom";

const App = () => {
  const [isLiked, setIsLiked] = useState(false);

  // Click handler for toggling like state
  const handleToggleLike = () => {
    setIsLiked((prevIsLiked) => !prevIsLiked);
  };

  return (
    

{isLiked ? "You liked this!" : "You haven't liked this yet."}

); }; export default App;

At the beginning of the component code, the handleToggleLike function is defined as a variable. Just like in HTML, it makes the mistake of calling the function immediately. It doesn’t call the function only when the button is clicked, but the function runs every time the component is rendered. 

Here, we don’t even need to call the function. We are supposed to directly pass it down.

Considering another option, you can always inline the function. 

Once you make the handleToggleLike an inline function, it won’t be called right away.

6. Using onClick to Handle Events in Custom Components

Custom components, like CustomLikeButton can’t directly respond to the click events because only the DOM elements can have the event handlers. To manage them, you have to render the DOM element inside the CustomLikeButton component and then pass the onClick prop to it. This way, the CustomLikeButton will act as a pass-through for your click event.

import React, { useState } from "react";
import ReactDOM from "react-dom";

// Custom Like Button Component
const CustomLikeButton = ({ isLiked, onToggleLike }) => {
  return (
    
  );
};

const App = () => {
  const [isLiked, setIsLiked] = useState(false);

  // Click handler for toggling like state
  const handleToggleLike = () => {
    setIsLiked((prevIsLiked) => !prevIsLiked);
  };

  return (
    

{isLiked ? "You liked this!" : "You haven't liked this yet."}

); }; export default App;

This code shows that your CustomLikeButton is first passed a prop of onPress and then it is passed further on to the button’s onClick. 

7. Conclusion

Event handlers play a crucial role in determining what actions to take as a response to specific events. The React’s onClick event handler helps handle click events on DOM elements effectively. 

In addition to event handlers, this article discussed synthetic events and then moved on to how the onClick handler works in class components, functional components, and custom components with appropriate examples. 

React onClick event handler is quite helpful to both experienced developers as well as beginners. They can come in handy in your React project. So, if you have any further doubts or queries regarding its use then feel free to share them in the comments section below. Our experts will get back to you with a suitable solution as soon as possible.

FAQs 

How do I set an onClick event in React?

You have to use an onClick attribute with the desired function to set an onClick event in React. For example, you want a function named handleClick to be called whenever the button is clicked. To do that, you either have to leverage the arrow function syntax in the onClick attribute or define the handleClick function separately. 

How do you pass an onClick event in React?

You need a parameter to pass the function. First, create a function that has the value as a parameter and then return the function from onClick prop. It’s the most common way to pass the value to onClick callback. 

What is the onClick handler?

React onClick handler is an event handler that allows you to call the function and take action whenever a specific element is clicked within your React application. 

Can I have two onClick events in React?

If you want to have two onClick events in React, you need multiple functions for the onClick event handler. You can create a new function that calls both functions you need to implement.

Comments


Your comment is awaiting moderation.