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.

Saturday, February 27, 2021

React Hooks

Earlier on in React, components were either class components or functional components. Functional components were Javascript functions that accepted props (data) to display and returned JSX.

Class components typically required more code but could store state variables and could use lifecycle methods. This made class components the go-to option for making API calls, processing user input, etc. Functional components became useful helpers for class components.

With the release of React 16.8 in 2019, React Hooks have finally become available to use in our production applications. This allows React developers to make functional components stateful. Instead of using a class component to hold stateful logic, we can use functional components.

React Hooks are not available in class-based components — but instead they allow you to use React without JavaScript classes. If you prefer to use functions instead of classes (which is recommended in JavaScript) you can simply start using Hooks without worrying about migrating your whole apps to classes.

Hooks enable you to use “class-features” In React by providing a set of built-in functions such as:

  • The useState() hook for using states from function components,
  • The useEffect() hook for performing side effects from function components (It's equivalent to life-cycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount in React classes). 

Hook State

let’s set up a component with state, the hooks way.


import React from "react";
const HookDemo = () => {
  return (
    <div>
      <h2>React Hooks</h2>
    </div>
  );
};
export default App;

 

And now, let’s use a React hook. We’ll add in some state to the component . To do so, we’ll import the useState hook from React at the top of the App.js file:


import React, { useState } from 'react';

Then we’ll apply the useState hook at the top of the App component function, to set up state functionality for the stuRoll:


const HookDemo = () => {
const [stuRollsetStuRoll] = useState();
 

There are three aspects to the useState hook:

1.   The argument to useState is its initial value. Therefore, with useState(), we are setting the initial value of stuRoll to a blank value.

2.   The useState method destructures your state object into an array of two values. The first one is the current value of the variable that is being tracked in the component state. Therefore, in const [stuRollsetStuRoll] = useState()stuRoll represents that current value. It becomes a constant that can be used in the component code.

3.   The second value returned from the useState function is a function itself. This function updates the paired state variable. So setStuRoll updates the stuRoll value.

Within the App component, let’s create a helper method, called updateDataWith this method, the input element will set the stuRoll in the hook state. How?

This helper will call the new setStuRoll function and update the student Rollno.

const ReactDemo = () => {

const [stuRollsetStuRoll] = useState(0);

  const updateData = () => {

    setStuRoll(10);

    console.log("Updated RollNo"stuRoll);
  };

  return (
    <div>
 <h2>Hooks | Function Component Based</h2>
      <h3>RollNo: {stuRoll}</h3>
      <button onClick={updateData}>Update</button>
    </div>
  );
};

export default ReactDemo;


Comparison to traditional class Component state

Let’s compare the App component function above with the more traditional class component state approach:

import React, { Component } from "react";

class StateDemo extends React.Component {
  constructor() {
    super();
    this.state = {
      stuRoll: 0,
    };
  }
  updateData = () => {
    this.setState({ stuRoll: 10 });
  };
  render() {
    return (
      <div>
        <h2>State | Class Component Based </h2>
        <h3>RollNo: {this.state.stuRoll}</h3>
        <button onClick={this.updateData}>Update</button>
      </div>
    );
  }
}
export default StateDemo;




Take note of the differences between this function version and the class version. It’s already much more compact and easier to understand than the class version, yet they both do exactly the same thing. Let’s go over the differences:

  • The entire class constructor has been replaced by the useState Hook, which only consists of a single line.
  • Because the useState Hook outputs local variables, you no longer need to use the this keyword to reference your function or state variables. Honestly, this is a major pain for most JavaScript developers, as it’s not always clear when you should use this.
  • The JSX code is now cleaner as you can reference local state values without using this.state.

Hook with Multiple states

import React, { useStateuseEffect } from "react";

const ReactDemo = () => {
  const [stuRollsetStuRoll] = useState(0);
  const [stuNamesetStuName] = useState("---");

  // Update the data of the component
  const updateData = () => {
    setStuRoll(10);
    setStuName("Pankaj");
  };

  return (
    <div>
      <h2>Hooks with Multiple States</h2>
      <h3>RollNo: {stuRoll}</h3>
      <h3>Name: {stuName}</h3>
      <button onClick={updateData}>Update</button>
    </div>
  );
};

export default ReactDemo;




The Rules of Hooks

  1. Hooks can only be called at the Top Level, it can't be called inside the loops or condition or nested functions.
  2. Hooks can only be called in the React Function or Custom Hooks, never use hooks in the regular javascript function.

Hooks Effect 

The Hooks Effect enables us to conduct collateral effects within the components function. The Hooks Effect will not use the lifecycle methods of the components, and these methods exist in the class components. Hooks Effect is similar to componentDidUpdate(), componentDidMount() lifecycle methods.


import React, { useStateuseEffect from "react";

const ReactDemo = () => {
  const [stuRollsetStuRoll] = useState(0);
  const [stuNamesetStuName] = useState("---");

  // Similar to componentDidMount() and componentDidUpdate

  useEffect(() => {
    console.log("Hooks Effects called ");
  });

  // Update the data of the component
  const updateData = () => {
    setStuRoll(10);
    setStuName("Pankaj");
  };

  return (
    <div>
      <h2>Hooks with UseEffect</h2>
      <h3>RollNo: {stuRoll}</h3>
      <h3>Name: {stuName}</h3>
      <button onClick={updateData}>Update</button>
    </div>
  );
};
export default ReactDemo;



In the above code, we invoke “useEffect” to inform the React to execute the “effect” method after reddening the modifications in the DOM. As we declare the effects in a component, the effects can use the state and props. React implements the effects after each render. Effects may also define how to do “clean up”.

Side effects contain usual properties that every web application have to conduct, like:

·       DOM Updation

·       Consuming and Retrieving data from an API Server.

·       Establishing Subscription 


Side Effects

we categorize side effects into two types:

  • Effects with Cleanup: After updating the DOM, we have to clean up some effects. For example, when we need to establish a subscription for any explicit data source, it is essential to clean up the memory to ensure that there is no memory leak.
  • Effects without Cleanup: We use Effects without Cleanup in effect that does not obstruct the browser in screen updation. Examples of Effects that do not need cleanup are Network requests, Manual DOM mutations, etc.

Sunday, February 21, 2021

React Components Lifecycle

We have learned so far that the React web applications are actually a collection of independent components that run according to the interactions made with them. Each component in React has a life-cycle that you can monitor and change during its three main phases. There are three phases: Mounting, Updating, and Unmounting. You can use life-cycle methods to run a part of code at particular times in the process or application. You can refer to the below diagram to get a visual idea of the life-cycle methods and their interactions in each phase.

Mounting

Mounting is the phase when the component is mounted on the DOM and then rendered on the webpage. We call these methods in the following order when an element is being created and inserted into the DOM:

  • componentWillMount()
  • render()
  • componentDidMount()

componentWillMount(): This function is called right before we mount the component on the DOM. So after this method executes, the component gets mounted on the DOM. It executes this method before the first render of the React application. So all the tasks that have to be done before the component mounts are defined in this method.

render(): This function mounts the component on the browser. 

componentDidMount(): We invoke this function right after the component is mounted on the DOM i.e., this function gets called once after the render() function is executed for the first time. Generally, in React applications, we do the API calls within this method.


Updating

We call the methods in this phase whenever State or Props in a component get updated. This allows the React application to “react” to user inputs, such as clicks and pressing keys on the keyboard, and ultimately create a responsive web user interface. These methods are called in the following order to carry on the update of the component:

  • componentWillReceiveProps()
  • setState()
  • shouldComponentUpdate()
  • componentWillUpdate()
  • render()
  • componentDidUpdate()

componentWillRecieveProps(): We call This function before a component gets its props reassigned. 

setState(): This function can be called explicitly at any moment. This function is used to update the state of a component.

shouldComponentUpdate(): This function is called before rendering a component and tells React whether it should update the component on receiving new props or state. It takes the new Props and new State as the arguments and returns whether or not to re-render the component by returning either True or False.

componentWillUpdate(): This function is called once before the render() function is executed after the update of State or Props.

render(): The component gets rendered when this function is called.

componentDidUpdate(): This function is called once after the render() function is executed after the update of State or Props.


Unmounting

This is the last phase of the life-cycle of the component where the component is unmounted from the DOM. This phase has only one method:

componentWillUnmount(): This function is called once before we remove the component from the page and this marks the end of the life-cycle.

Now that we are familiar with all the life-cycle methods of React components, let us now look at an example to see how each function is implemented in the application code: 

DisplayCycle.js

import React from "react";
import DisplayChild from "./DisplayChild";

class DisplayCycle extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name: "Pankaj" };
    console.log("Constructor");
  }
  componentWillMount() {
    console.log("componentWillMount Parent");
  }
  componentDidMount() {
    console.log("componentDidMount Parent");
  }
  shouldComponentUpdate() {
    console.log("shouldComponentUpdate parent");
    return true;
  }
  componentWillUpdate() {
    console.log("componentWillUpdate() called");
  }

  componentDidUpdate() {
    console.log("componentDidUpdate() called");
  }
  componentWillUnmount() {
    console.log("componentWillUnmount() called");
  }
  switchState = () => {
    this.setState({ name: "pankaj Kapoor" });
  };
  render() {
    console.log("render Parent");
    return (
      <div>
        <input type="text" value={this.state.name} />
        <DisplayChild firstname={this.state.name} />
        <button onClick={this.switchState}>Click Me</button>
      </div>
    );
  }
}

export default DisplayCycle;

Output: