More

    React Events: Everything Defiend About It

    Introduction to React Events:

    The actions to which JavaScript can respond are called events. For example: even if you click on a button then clicking on that button is an event. After clicking the button the task that the button is going to perform is assigned by the Event handler.

    Other commonly used events are as follows:

    • Clicking an element
    • Submitting a form
    • Scrolling page
    • Hovering an element

    So, the basic idea about the events is clear. Developers in JavaScript must be familiar with these terms so it’s not difficult or new for them to understand. So, basically, an event is some sort of action that could be triggered which could be a result of either the user action or a system-generated event. The events examples are like:  loading a web page, a mouse click, resizing of the window, pressing a key, and many more interactions are called events.

    Event Handling in React: 

    Handling events with React elements is very similar to handling events on DOM elements. There are some syntactic differences:

    • React elements are named using camelCase, rather than lowercase.
    • With JSX, you pass a function as the event handler, rather than a string.
    • In React we cannot return false in order to prevent a default behavior. We must call preventDefault event explicitly, i.e. write it by oi=ur own in our code while developing the application in order to prevent the default behavior. 

     

    In HTML we write events as follows:

    <button onclick= “handleClick()”>Click Me</button>

     

    In React we write events as follows:

    <button onClick={handleClick}>Click Me</button> //as Function Component

    <button onClick={this.handleClick}>Click Me</button> //as Class component

     

    One cannot return false to prevent default behavior to React. We must call preventDefault explicitly. For example:

     

    In HTML:

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

     

    In React: 

    Function handleClick(e) {

    e.preventDefault();

    console.log(Clicked.’);

    }

     

    <a href=”#” onClick={handleClick}> Click me </a> 

    If the events are handled by React then it is known as Synthetic Events. A synthetic event is actually a cross border wrapper for the browser’s native event.  

    Just like in any other framework, in React, without event handlers, we would not be able to create amazing, responsive and interactive web applications that would respond to the user at every touch. Event handling is a very crucial part of React as it makes sure that React keeps a track of every action performed by the user. These actions might include resizing the window, scrolling through a page, or even clicking a link is processed and detected by the event handlers. 

    React Event List:

    The event handlers below are triggered by an event in the bubbling phase. In order to register an event handler for the capture phase, append Capture to the event name, for example: Instead of using onClick we have to use onClickCapture to handle the click event in the capture phase. The event property called onClick is passed to the function called clickHandler. 

    • Clipboard events: 
    • onCopy
    • onCut
    • onPaste

    • Composition events:
    • onCompositionEnd
    • onCompositionStart
    • onCompositionUpdate

    • Keyboard events:
    • onKeyDown
    • onKeyPress
    • onKeyUp

    • Focus events:
    • onFocus
    • onBlur

    • Form events:
    • onChange
    • onInput
    • onInvalid
    • onSubmit

    • Mouse events:
    • onClick
    • onContextMenu
    • onDoubleClick
    • onDrag
    • onDragEnd
    • onDragEnd
    • onDragEnter
    • onDragExit
    • onDragOver
    • onDragLeave
    • onDragStart
    • onDrop
    • onMouseDown
    • onMouseEnter
    • onMouseLeave
    • onMouseMove
    • onMouseOut
    • onMouseOver
    • onMouseUp

    • Pointer events:
    • onPointerDown
    • onPointerMove
    • onPointerUp
    • onPointerCancel
    • onGotPointerCapture
    • onLostPointerCapture
    • onPointerEnter
    • onPointerLeave
    • onPointerOut
    • onPointerOver

    • Selection Events:
    • onSelect

    • Touch Events:
    • onTouchCancel
    • onTouchEnd
    • onTouchMove
    • onTouchStart

    • UI events:
    • onScroll

    • Wheel Events:
    • onWheel

    • Media Events:
      • onAbort
      • onCanPlay
      • onCanPlayThrough
      • onDurationChange
      • onPause
      • onPlay
    • onPlaying
    • onProgress
    • onRateChange
    • onSeeked
    • onSeeking
    • onStalled
    • onSuspend
    • onTimeUpdate
    • onVolumeChange
    • onWaiting

    • Image Events:
    • onLoad
    • onError

    • Animation Events:
    • onAnimationStart
    • onAnimationEnd
    • onAnimationIteration

    • Transition Events:
    • onTransitionEnd

    • Other Events:
    • onToggle

    Synthetic Events:

    For each event, React also creates a SyntheticEvent which can be passed into callback functions or event handlers as well as contains details of the event. 

    Defining Events:

    In order to define the events in JSX, we need to add the camelCased event as well as the corresponding event handler or the callback function as one of the properties of JSX representing the React element:

    The parenthesis over there are used to connect those events to their respective event properties. However, they do not create inline events in the DOM. 

    Passing Arguments to Event Handlers

    Most commonly the developers want to pass an extra parameter to an event handler, inside a loop. For example: Let us assume that the id is the row ID then any of the following would work:

    The above two lines are equivalent and interchangeable and both of them use 

    Function.prototype.bind as well as  Arrow functions respectively. In both, the above cases the argument e which over there is representing a React event will be passed as the second argument after the first argument id. While with an arrow function we need to pass it explicitly but we can see that bind is used and with bind, any other arguments further are automatically forwarded. 

    Most of the behavior that we can see in an application, revolves around events. Events can be triggered in a vast number of ways and we build applications to listen for the events in order to do something else for them. One might be very comfortable while working with the events based on their experience in JavaScript but React has a very different and unique way of handling the events. Rather than targeting the DOM events directly, what React does is it wraps them in their own event wrapper but that can be talked about later. Let us now see how to actually create, add and listen for the React events.

    Creating Events:

    Let us start by creating a form that has an input and a button. After that, an event must be triggered when a value is entered and what the button is used for is to call a function that will reverse that value. The things that should be included are:

    • A field that is an empty input field which allows the user for entering text.
    • An onChange event is needed to be triggered when users enter values in the input. For this, we need to call the function: handleChange(). This function is used for setting a new state for the input.
    • When the “reverse Text” button is to be clicked, another event must be triggered. This time we need to call the function: handleReverse(). This function is needed for setting up a new state for reversedText.

    Listening to Component Events:

    We know that we can only listen to the events on the DOM elements. In the beginning of this post we already touched on this topic but we know that the components of React are the Wrappers of the DOM elements which means that we already have a layer which we need for passing through for listening to the events. The way around this hindrance would be passing the event

    handler as a prop to a child component and after that, the prop is passed down to the click event as an attribute. 

    Adding Event Listeners:

    There might be certain times when we would want to make use of certain DOM events that get triggered when the component is mounted. We can take the example of the resize event when we want to see the width of the window whenever it gets resized. If we are creating a component and try it out, we will need to add the event listeners: handleResize() and the event type that we have. Then the event listener will get added when the component is mounted which means that the component we made is listening to the browser window actively and it will display the width when it gets updated.

    Conclusion:

    We have covered quite a bit about the various aspects of the React Events but the large ground we have covered is a very small amount of space when it comes to development using React. Here we have also learned that React does not connect to a DOM event directly but rather there are Synthetic events that are wrapped for DOM events. We also dug into the process of creating new event listeners so that they are attached to the all-new Synthetic events and from there, we made sure that a component will get updated when those particular events are triggered. This article covered all the necessary topics on React events that are required for the beginner level and also covers a few concepts that will help you in higher levels of understanding. Hope this article was helpful for you and you develop wonderful applications using React.

     

    Recent Articles

    React Fragment: Find out what we encountered.!

      React Fragment: Hello Devs, in my journey of learning react I came across some frontend conditions where I had to render multiple react components,...

    React Admin: Documentation | Features | Dahboard | Templates

      React Admin is a framework for the front-end development of data-driven applications. That is operating in a browser over the top of REST or...

    React Hooks

      A hook is a component that allows us to use the features of React and state without defining a class. This feature is added...

    React Animation: A definitive guide

    React Animations Add-ons The ReactTransitionGroup add-on is a lower-level Applications Program Interface (API) component for creating react animations. And the ReactCSSTransitionGroup, is a component used...

    Create React App: A Complete guide for Beginners

      Create React App is the modern way of building an official Single Page React Application. It sets up a comfortable environment for building react...

    Related Stories

    Leave A Reply

    Please enter your comment!
    Please enter your name here