React Events

 

An event is an action that could be triggered as a result of the user action or system generated event. For example, a mouse click, loading of a web page, pressing a key, window resizes, and other interactions are called events.

React has its own event handling system which is very similar to handling events on DOM elements. The react event handling system is known as Synthetic Events. The synthetic event is a cross-browser wrapper of the browser’s native event.

React Events

Handling events with react have some syntactic differences from handling events on DOM. These are:

  1. React events are named as camelCase instead of lowercase.
  2. With JSX, a function is passed as the event handler instead of a string. For example:

Event declaration in plain HTML:

  1. <button onclick=“showMessage()”>  
  2.        Hello JavaTpoint  
  3. </button>  

Event declaration in React:

 
  1. <button onClick={showMessage}>  
  2.       Hello JavaTpoint  
  3. </button>  

3. In react, we cannot return false to prevent the default behavior. We must call preventDefault event explicitly to prevent the default behavior. For example:

In plain HTML, to prevent the default link behavior of opening a new page, we can write:

 
  1. <a href=“#” onclick=“console.log(‘You had clicked a Link.’); return false”>  
  2.     Click_Me  
  3. </a>  

In React, we can write it as:

 
  1. function ActionLink() {  
  2.     function handleClick(e) {  
  3.         e.preventDefault();  
  4.         console.log(‘You had clicked a Link.’);  
  5.     }  
  6.     return (  
  7.         <a href=“#” onClick={handleClick}>  
  8.               Click_Me  
  9.         </a>  
  10.     );  
  11. }  

In the above example, e is a Synthetic Event which defines according to the W3C spec.

Now let us see how to use Event in React.