Easy Way to understand onClick Event Handler in ReactJS

ReactJS Event Handling

Any web application, you create typically tends to have user interaction. When the user interacts with your application events are fired, for ex: mouse clicks, mouse hovers, key presses, change even, etc. The application must handle such events and execute the necessary code. So, in this article, we will learn how to handling the event in Reactjs.

We will focus on just the click event but the concepts hold good for another event as well. Let’s begin with functional components:

const Click = () =>{
return(
<div>
<button>Click </button>
</div>
)
}

Output:

reactjs event handling

  1. In the above code, we have created a functional component called Click().
  2. The function returns click button.
  3. And render the Click() function.
  4. See the output, our click button is displayed. When the user clicks on this button, a click event is fired. So, our goal is to capture that click event and execute some basic code.

 

The first point you have to make note of is: React events are named using camelcase rather than lowercase. In HTML or vanilla JavaScript, you would specify “onclick” attribute but in React it has to be camelcase so we put ‘c’ in uppercase “onClick”.

The second point is with JSX, You pass a function as the event handler rather than a string. So, we pass clickHandler within the curly braces. Now, let’s define the clickHandler function. Remember in JS, it is very much possible to define a function within another function. So, Inside the Click() functional components we can define our clickHandler function. Within the body, we simply log to the console “button clicked”.

const Click = () =>{
function clickHandler(){

console.log("button clicked");

}
return(
<div>
<button onClick={clickHandler}>Click </button>
</div>
)
}

Output:

READ ALSO  How to Map Array to Components in React jS?

reactjs event handling
See the output, after we clicked the button the message will display in the console log. If we click the button twice, the number 2 will display. So, our clicked event handling works as expected.

 

Leave a Reply