For enquiries call:

Phone

+1-469-442-0620

Easter Sale-mobile

HomeBlogWeb DevelopmentHandling React Events - A Detailed Guide

Handling React Events - A Detailed Guide

Published
29th Feb, 2024
Views
view count loader
Read it in
8 Mins
In this article
    Handling React Events - A Detailed Guide

    Event handling essentially allows the user to interact with a webpage and do something specific when a certain event like a click or a hover happens. When the user interacts with the application, events are fired, for example, mouseover, key press, change event, and so on. The application must handle events and execute the code. In short, events are the actions to which javascript can respond. Get a deeper understanding of usereducer in React. 

    The actions to which JavaScript can respond are called events. Handling events with react is very similar to handling events in DOM elements. To get a better understanding of web development, check out Full Stack developers course.  Below are some general events that you would see in and out when dealing with React-based websites:  

    • Clicking an element  
    • Submitting a form 
    • Scrolling page 
    • Hovering an element  
    • Loading a webpage 
    • Input field change 
    • User stroking a key 
    • Image loading 

    React Events: Naming  

    Handling events with react is very similar to handling events in DOM elements, although there are some syntactic differences. 

    •   React events are written in camelCase. 
    •   A function is passed as the event handler rather than string. 

    The way to write events in html / DOM is below:  

    <button onclick=”handleClick()”>click me</button> 

    onclick is written in lower case in html as shown above and what action to take when this onclick event triggers is taken care of by handleClick.

    In React, events are named using camel case and you pass a function as event handler as shown below:  

    Like in a functional component, event is written like below:  

    <button onClick={handleClick}>click me</button>  

     In class based component ,event is written like below  

    <button onClick={this.handleClick}>click me</button> 

    How to Define React Events?

    Events are normally used in combination with functions, and the function is not executed until the event occurs, and the combination of event, HTML element, and javascript function is called binding which means to map all three. 

    Generic syntax is:  

    <html element event=”javascriptfunction”> 

    Example:  

    Create a button element and what happens when onClick event triggered is driven by the function which is func() shown below  

    <button onClick=”func()”>click me</button> 

    Let’s see some of the event attributes:   

    • onmouseover: The mouse is moved over an element 
    • onmouseup: The mouse button is released 
    • onmouseout: The mouse  is moved off an element 
    • onmousemove: The mouse is moved 
    • Onmousedown: mouse button is pressed  
    • onload: A image is done loading 
    • onunload: Existing the page  
    • onblur: Losing Focus  on element  
    • onchange: Content of a field changes 
    • onclick: Clicking an object  
    • ondblclick: double clicking an object  
    • onfocus element getting a focus  
    • Onkeydown: pushing a keyboard key 
    • Onkeyup: keyboard key is released 
    • Onkeypress: keyboard key is pressed  
    • Onselect: text is selected 

    These are some examples of events: 

    <!DOCTYPE html> 
    <html> 
    <head> 
         <title> Events </title> 
           <script> 
             function testApp (){ 
                    alert((“Hello Event”); 
           </script> 
    </head> 
    <body> 
             <button onClick=”testApp()”>test Clicked</button>  
             <p ondblclick=”testApp()”>test double Clicked</p> 
    </body> 
    </html> 

    What are Synthetic React Events?

    When you specify an event in JSX, you are not directly dealing with regular DOM events, you are dealing with a react event type called a synthetic event.It's a simple wrapper for native event instances and every synthetic event created needs to be garbage-collected which can be resource intensive in terms of CPU. The synthetic event object has properties mentioned below:  

    • Boolean isTrusted  
    • DOMEvent nativeEvent 
    • number timeStamp   
    • void preventDefault() 
    • number eventPhase 

    Synthetic events provide an interface and reduce browser inconsistencies and the event contains required information for its propagation to work. Synthetic event is reused for performance reasons in the browser, A synthetic event is a cross-browser wrapper around the browser’s native event it has the same interface as the native event. Synthetic events are delegated to the document node. Therefore native events are triggered first and the events bubble up to document, after which the synthetic events are triggered. The synthetic event object will be reused and all the properties will be nullified after the event callback has been invoked and this is for performance reasons.

    The workflow of synthetic event in react is:  

    Element ---- > Event ---- > synthetic event  ---- > handler(e) 
                                  |                                                      | 
                                  |  _______  Component ________| 
    umber timeStamp 

    Basics of React Event Handling 

    Let’s explore how to handle events in react and we will showcase the click event and how it holds good for other types of events. Let’s start with functional components by creating a  

    file as clickAppHandler.js.In this file let’s create a  functional component  as shown below 

                           Import React from ‘...react’ 
                           function clickAppHandler() { 
                                  function clickHandler() { 
                                          console.log(‘clicked’) 
                                           } 
                                    return ( 
                                          <div> 
                                            <button onClick={clickHandler}>Click</button> 
                                          </div> 
                                    ) 
                           } 
                         export default clickAppHandler  

    When onClick event triggers clickHandler function is called as shown below and when you click the button console will print the string “clicked” 

    After this you need the add a component in the app component. In our code above you can see on click we pass the function as event handler and you will notice that we haven't added parentheses as it becomes a function, and we do not want that and we want handler to be a function not a function call. When a new component is rendered its event handler functions are added to the mapping maintained by the react.When the event is triggered and it hits and DOM object ,react maps the event to the handler, if it matches it calls the handler. The event handling in react is declarative and the advantage of declarative way to handlers is that they are part of the User interface structure. Worried how to kick-start your career in web development? Enroll in the best Online Web Development course.     

    Let’s take a look at event handling in class components 

                          Import React, { Component } from ‘...react’ 
                           class TestApp extends Component { 
                                clickHandler() { 
                                    console.log(“clicked”) 
                                  }  
                                 render(){ 
                                        return( 
                                           <div> 
                                              <button onClick={this.clickHandler}>Click me </button> 
                                           </div> 
                                         ) 
                                   } 
                              } 
                         export default TestApp 

    You cannot return false to prevent default behaviour in React. You must call preventDefault explicitly. 

     In HTML it looks like below: 

    <a href =”#” onclick=”console.log(‘Clicked’);return false”>Click</a> 

    Output: It will print “Clicked”  

    And in React, like this:  

    function clickHandle(e) { 
         e.preventDefault(); 
         console.log(“Handled”); 
     } 
    <a href=”#” onClick={clickHandle}> Click </a> 

    Output : console will print “Handled”  

    There are some  event handlers triggered by an event in the bubbling phase which is the same as with the normal DOM API; simply attach a handler to an eventual parent of an element and any events triggered on that element will bubble to the parent as long as it's not stopped via stopPropagation along the way 

     <div onClick={this.handleClick}> <button>Click me</button> </div> 

    Below are some of the event handlers triggered in the bubbling phase:  

    MouseEvents 

    • onClick 
    • onDrag 
    • onDoubleClick 

    Keyboard Events 

    • onKeyDown 
    • onKeyPress 
    • onKeyUp 

    Focus Events 

    • onFocus   onBlur 

    To capture an event handler for the capture phase, append capture to the event name. For example, instead of using onClick, use onClickCapture to handle the click event.  

    Capture event example:  

                    <div onClickCapture={this.handleClickViaCapturing}> <button onClick={this.handleClick}> Click me  </button> </div> 

    Event Handling in React: Additional Examples

    Example 1  

                         Import React from ‘...react’ 
                           function clickAppHandler() { 
                                  function clickHandler() { 
                                          console.log(‘clicked’) 
                                           } 
                                    return ( 
                                          <div> 
                                            <button onClick={clickHandler}>Click</button> 
                                          </div> 
                                    ) 
                           } 
                         export default clickAppHandler 

      Example 2   

        This example is along with HTML in a single file  

    <!DOCTYPE html> 
    <html> 
    <head> 
    <title> Events </title> 
    <script> 
    function testApp (){ 
          alert((“Hello Event”); 
    </script> 
    </head> 
    <body> 
          <button onClick=”testApp()”>test Clicked</button>  
          <p ondblclick=”testApp()”>test double Clicked</p> 
    </body> 
    </html> 

    Adding Events 

    Below example is how you add an event. Highlighted in bold 

                         Import React from ‘...react’ 
                           function clickAppHandler() { 
                                  function clickHandler() { 
                                          console.log(‘clicked’) 
                                           } 
                                    return ( 
                                          <div> 
                                            <button onClick={clickHandler}>Click</button> 
                                          </div> 
                                    ) 
                           } 
                         export default clickAppHandler  

    Passing Arguments to Event Handler

    There are two ways arguments are passed to event handler  

    Arrow function  

    <button onClick={(e) => this.handleClick(id,e)}>Click</button> 

                   onClick is the event 

                   e is the event object  

                   id can be state or props or some data 

    Bind method  

    <button onClick={this.handleClick.bind(this,id)}>Click</button> 

     In this case event object is automatically passed 

    In both methods e represents the react event and its passed after the ID as second argument,With an arrow function this event e is passed explicitly but with bind method its automatically passed. 

                                        Import React,{ Component } from “react”; 
                                           class TestApp extends Component { 
                                             state = { 
                                                         id: 2, 
                                                        Name: “TestApp Dummy” 
                                                  }; 
     
                                                             //arrow function  
                                                  handleClick = (id,e) => { 
                                                         console.log(id); 
                                                         console.log(e); 
                                                    }; 
                                                 handleArg = (e) => { this.handleClick(this.state.id,e);} 
                                                            render() { 
       return ( 
          <div> 
             <h1> TestApp,{this.state.name}</h1> 
             <button> onClick={this.handleArg}>Display </button> 
           </div> 
    ); 
     } 
    }  

    The react event is an object and obtained from react. Instead of creating a separate function for passing argument, you can directly pass the anonymous arrow function as shown in the render function below: 

    render() { 
      return ( 
                                               <div> 
                                                   <h1> TestApp,{this.state.name}</h1> 
                                              <button  onClick={ e => {                           this.handleClick(this.state.id,e); 
                                                             }}>Display</button> 
                                                 </div> 
                                                    ); 
                                               } 
                                          } 
     
    Output:   click on button  “TestApp Dummy “ 
                    
    Let’s see only how bind method looks like in the render function 
     
    render() { 
                                           return ( 
                                                 <div> 
                                                   <h1> TestApp,{this.state.name}</h1> 
                                                     <button onClick={this.handleClick.bind(this, this.state.id)}>Display</button> 
                                                    </div> 
                                                       );  
                                                   } 
                                                } 

    Output: this will display the h1 tag and when you click the button handleClick function gets invoked and the console will display id of the state object as shown above. 

    Are you ready to unlock endless possibilities with Python? Join our Python Developer Course with certification and embark on a journey towards a successful career. Don't miss out on this unique opportunity!

    Building a Practice to Thoroughly Understand Events  

    This blog focuses on event handling, which in turn teaches about event handlers declared in JSX markup.This approach helps in tracking down the element mapped with events in an easy way. We also learned how to handle multiple event handlers in a single element by using JSX attributes.we also learned about ways to bind event handler and  parameter values. Then we learned about synthetic events which are abstractions around native events. The best way you can retain this learning is by practicing more and tackling the complexities that may arise as you practice. You can find several tutorials on the internet or share your questions with us here. Happy learning! 

    Profile

    Ankur Pandita

    Author

    I have been working as a Software Engineer for 8.5 years now, majorly working with Python, Golang and bash. I use tools such as AWS, GCP, OCI for cloud computing and docker, Kubernetes, Terraform for deployment. I have experience working with Networking, Routing, Load balancing, DNS and a good understanding of the IP, TCP, UDP, HTTP, and SSL protocols as well.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon