Sunday, February 28, 2021

React Events

In web development, events represent actions that happen in the web browser. By responding to events with event handlers, you can create dynamic JavaScript applications that respond to any user action, including clicking with a mouse, scrolling along a webpage, touching a touch screen, and more.

In React apps, you can use event handlers to update state data, trigger prop changes, or prevent default browser actions. 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. SyntheticEvent closely emulates the standard browser event, but provides more consistent behavior for different web browsers. 

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:

<button onclick="showMessage()">

       Hello JavaTpoint

</button>

Event declaration in React:

<button onClick={showMessage}>

      Hello JavaTpoint

</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:

<a href="#" onclick="console.log('You had clicked a Link.'); return false">

    Click_Me

</a> 

In React, we can write it as:

function ActionLink() {

  function handleClick(e) {

      e.preventDefault();

      console.log('You had clicked a Link.');

  }

  return (

      <a href="#" onClick={handleClick}>

            Click_Me

      </a>

  );

} 

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.


onClick Event handler in React

The React onClick event handler enables you to call a function and trigger an action when a user clicks an element, such as a button, in your app.

To listen to events in React, add the onClick attribute, which is the event handler, to the target element. This specifies the function to be executed when that element is clicked.

import React, { Component } from "react";
class ShowAlert extends Component {
  showAlert() {
    alert("I'm an alert");
  }
  render() {
    return <button onClick={this.showAlert}>show alert</button>;
  }
}
export default ShowAlert;
Output: 

In the example above, the onClick attribute is set to the showAlert function, which alerts a message. This means that whenever the button is clicked, the showAlert function is called, which, in turn, shows the alert box.

 

Handling events in class components

In JavaScript, class methods are not bound by default. Therefore, it’s necessary to bind functions to the class instance.

Binding in the render() method: One way to resolve the problem of binding is to call bind in a render function. This is done by binding it in the render() function. This method requires calling .bind(this) in the render() function.

<button onClick={this.showAlert.bind(this)}>show alert</button>

 

Binding in the constructor() method: If binding in the render doesn’t work for you, you can bind in the constructor. See an example below:

class ShowAlert extends Component {

  constructor(props) {

    super(props);

    this.showAlert = this.showAlert.bind(this);

  }

The first this.showAlert refers to the showAlert method. Since this is done in the constructor, this refers to the ShowAlert class component.

The second this.showAlert is also referring to the same showAlert() method, but we are now calling .bind() on it.

The final this is the context we are passing to .bind(), and it refers to the ShowAlert class component.

It’s also important to note that if showAlert isn’t bound to the class instance, it won’t be able to access this.setState because this will be undefined. This is another important reason to bind event handling functions.

Binding in the arrow function: You can handle events in class components by binding them with the fat arrow function. ES7 class properties enable bindings at the method definition, as shown in the example below. By definition, an arrow function expression has a shorter syntax than a function expression and does not have its own thisargumentssuper, or new.target.

showAlert=()=> {

    alert("I'm an alert");

  }

 

onChange Event handler in React

In the below example, we have used only one component and adding an onChange event. This event will trigger the changeText function, which returns the company name.

import React, { Component } from "react";
class DemoOnChange extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tutorialName: "",
    };
  }
  changeText(event) {
    this.setState({
      tutorialName: event.target.value,
    });
  }
  render() {
    return (
      <div>
        <h2>onChange Event Example</h2>
        <label htmlFor="name">Enter Tutorial name: </label>
        <input
          type="text"
          id="companyName"
          onChange={this.changeText.bind(this)}
        />
        <h4>You entered: {this.state.tutorialName}</h4>
      </div>
    );
  }
}
export default DemoOnChange;

Output

When you execute the above code, you will get the following output.

After entering the name in the textbox, you will get the output as like below screen.

 

onSubmit Event handler in React

You can control the submit action by adding an event handler in the onSubmit attribute:

Example

import React, { Component } from "react";

class MyForm extends React.Component {

  constructor(props) {

    super(props);

    this.state = { username: "" };

  }

  mySubmitHandler = (event=> {

    event.preventDefault();

    alert("You are submitting " + this.state.username);

  };

  myChangeHandler = (event=> {

    this.setState({ username: event.target.value });

  };

  render() {

    return (

      <form onSubmit={this.mySubmitHandler}>

        <h2>onSubmit Event Example</h2>

        <p>Enter your name, and submit:</p>

        <h1>{this.state.username}</h1>

        <input type="text" onChange={this.myChangeHandler} />

        <input type="submit" />

      </form>

    );

  }

}

export default MyForm;

Note that we use event.preventDefault() to prevent the form from actually being submitted.