React Events

Back to home
Logicmojo - Updated Aug 28, 2021



What do you mean by React Events?

An event is a type of action that can be initiated by a user action or a system-generated event. A mouse click, a web page loading, tapping a key, window resizing, and other interactions are examples of events. Synthetic Events is the name of the react event handling system. The synthetic event is a cross-browser wrapper for the native event of the browser.


Adding Events

CamelCase syntax is used to write React events:
instead of onclick, use onClick.

Curly braces are used to write React event handlers:
instead of onClick="shoot()," use onClick="shoot."



Declaration of event in HTML

 
 <button onclick="Fun()">OnClick Event fired!</button>
                        


Declaration of event in React

 
<button onclick={Fun}>OnClick Event fired!</button>
                        


Example :

Let's put the Fun() function in Eventfunction() component



 
function Eventfunction() {
  const Fun = () => {
    alert("Let's learn Events");
  }

  return (
    <button onClick={Fun}>OnClick Event fired!</button>
  );
}

ReactDOM.render(<Eventfunction />, document.getElementById('root'));

                        


We can't return false in react to prevent the default behaviour. To prevent the default behaviour, we must explicitly call the preventDefault event. Consider the following scenario:



In HTML

 
<a href="#" onclick="console.log('Link will be clicked'); return false">  
        Please click the link!  
    </a>  
                        


In React

 
     function Activate() {  
        function handleClick(e) {  
            e.preventDefault();  
            console.log('Link will be clicked');  
        }  
        return (  
            <a href="#" onClick={handleClick}>  
                  Please click the link! 
            </a>  
        );  
    }  
                        


In the example above, e is a Synthetic Event that conforms to the W3C specification.


Passing Arguments

Use an arrow function to provide an argument to an event handler.



Example :

 
function Eventfunction() {
  const Fun = (s) => {
    alert(s);
  }

  return (
    <button onClick={Fun("Let's learn Events")}>OnClick Event fired!</button>
  );
}

ReactDOM.render(<Eventfunction />, document.getElementById('root'));

                        


React Event Object

The React event that triggered the method is accessible to event handlers.
The event in our example is the "click" event.



Example :

 
function EventFunction() {
  const Fun = (x, s) => {
    alert(s.type);
    /*
    The React event that triggered the function, 
    in this example the 'click' event, is represented by 's;. 
    */
  }

  return (
    <button onClick={(event) => Fun("Let's learn Events", event)}>
    OnClick Event fired!</button>
  );
}

ReactDOM.render(<EventFunction />, document.getElementById('root'));
                        


Handling Events

Using React to handle events is comparable to using DOM elements to handle events.
You give an event listener when the element is first rendered, rather than executing addEventListener as you would in Vanilla JavaScript.

There are some syntactic distinctions as well:

🚀 Instead of all lowercase, React events are named in camelCase (like onClick).
🚀 Instead of passing a string as the event handler, JSX allows you to supply a function. To ensure cross-browser compatibility, React uses its own event system.


To do this, React wraps native browser events in a SyntheticEvent structure and delivers them to React event handlers. These synthetic events were defined by React according to the W3C spec, ensuring cross-browser compatibility.
You may use methods like preventDefault() and stopPropagation() since React's SyntheticEvent has the same interface as a native browser event ().

The characteristics of a SyntheticEvent object are as follows:



 
boolean bubbles
string type
DOMEventTarget currentTarget
number eventPhase
boolean isTrusted
void persist()
DOMEvent nativeEvent
void stopPropagation()
boolean isDefaultPrevented()
boolean isPropagationStopped()
void preventDefault()
DOMEventTarget target
boolean defaultPrevented
number timeStamp
boolean cancelable
                        


A popular pattern when creating a class-based component is to make an event handler a method on the class.
The Toggle component generates a button that allows the user to toggle between "ON" and "OFF" states like the example below.
When a click event occurs, the handleClick() method changes the state, and the render() method displays the current state on the DOM.

React has a built-in functionality that "pools" its SyntheticEvents for performance. This means that when an event handler is called, all of the event.target's properties are set to null.
The event object can be reused by React elsewhere in our application by nullifying the properties after the callback has completed.
This is an excellent example of React's DRY, modular, and reusable purpose.
The browser does not need to allocate memory for a new object for each instance of an event because of event pooling. Instead, for all event occurrences, it will use the same in-memory event object.
The keys of the event object remain in place after the event handler completes its execution, but the values of each key are reset to null. This frees up memory, but the values of the executed event are lost in the process.
The properties can't be accessed asynchronously because of this nullification.
When an asynchronous function like setState() is called, it will attempt to access event attributes such as event.currentTarget.value, but since all of the event object's properties have been reset to null, the return value will be... null. No way!
We call event.persist() at the start of the function to prevent an event object from being pooled and so nullified.
This method removes the SyntheticEvent from the pool, and the event object will not be reused by subsequent DOM events; this permits asynchronous references to the event to be kept.
You can keep the data you require in a variable instead of using event.persist() (for example, const pool = event.target).
You'll probably get an error like Uncaught TypeError: Cannot read null property 'data'.


Passing Arguments to Event Handlers

It's typical to wish to give an extra parameter to an event handler inside a loop. If id is the row ID, for example, either of the following would work:



 
<button onClick={(e) => this.updateRow(id, e)}>Update Row</button>
<button onClick={this.updateRow.bind(this, id)}>Update Row</button>
                        


The two lines above are interchangeable and use arrow functions and Function.prototype.bind, respectively.
The e argument, which represents the React event, will be supplied as a second argument after the ID in both circumstances. With an arrow function, we must explicitly pass it, whereas with bind, any additional arguments are transmitted automatically.


Conclusion

So there you have it, your journey into the React Events. You are now able to know about handling events, adding events, passing arguments and so on.