image

React Tutorial

React Home React Intro React Get Started React ES6 - ES6 Classes - ES6 Arrow Functions - ES6 Variables - ES6 Array Methods - ES6 Destucturing - ES6 Spread Operator - ES6 Modules - ES6 Ternary Operator React Render HTML React JSX React Components React Class React Props React Events React Conditionals React Lists React Forms React Router React Memo React CSS Styling

React Hooks

What is a Hook? useState useEffect useContext useRef useReducer useCallback useMemo Custom Hooks

React Redux

What is a Redux? React Redux Example

React Exercises

React Quiz

React Class Components

In previous chapter, We had seen, the Components come in two types, Class components and Function components.

In the Previous version of React(16.8), Class components were the only way to track state and lifecycle on a React component. And Function components were considered as "state-less".

After React version (16.8), Function components are more prefered components but there are no current plans on removing Class components from React. the addition of Hooks in React, Function components are now almost equivalent to Class components.

in react, Components are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but work in isolation and return HTML via a render() function.

The components name should be start with upper case letter in React Application.

Creating a Class Component

Class Component has to include the extends React.Component statement, and this statement creates an inheritance to React.Component and allow your component access to the function of React.Component. And also Class Component requires the render() method, this method returns HTML.

Create a class component called School

class School extends React.Component {
  render() {
    return <h1>Hi, This is my School!</h1>;
  }
}

Now in your application has a class component called School and which returns to <h1/> element. Use this component similar syntax as normal HTML : <School />. In your React Application display the School in "root".

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

in React Application :

 import React from 'react';
  import ReactDOM from 'react-dom';

  class School extends React.Component {
    render() {
      return <h2>Hi, This is my School!</h2>;
    }
  }

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

Output :

image

Constructor function

The constructor is a method used to initialize an object's state in a class. It automatically called during the creation of an object in a class.

In React, the concept of a constructor is the same, there is no different normal constructor. The constructor in a React component is called before the component is mounted. In other way, It can be used to bind event handlers to the component or initializing the local state of the component

Component properties should be kept in an object called state.

When you are using constructor in React component, you need to call super() method before any other statement. Which executes the parent component's constructor function, and your component has access to all the functions of the parent component (React.Component). If you do not call super() method, this.props will be undefined and display errors(bugs).

Creat a constructor() in School component, Add with color property

class School extends React.Component {
    constructor() {
      super();
      this.state = {color: "green"};
    }
    render() {
      return <h1>Hi, This is my School!</h1>;
    }
  }
  

Use color property in render() function.

class School extends React.Component {
    constructor() {
      super();
      this.state = {color: "green"};
    }
    render() {
      return <h1>Hi, This is my {this.state.color} School!</h1>;
    }
    }
  

In React Application

class School extends React.Component {
    constructor() {
      super();
      this.state = {color: "green"};
    }
    render() {
      return <h1>Hi, This is my {this.state.color} School!</h1>;
    }
    }

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

Output :

image

Constructors are used for two key objectives:

  • To initialize the local state of the component by assigning an object to this.state.
  • To bind event handlers that occur in the component.

Props

“props” stands for properties. It is a special keyword in React which is used for passing data from one component to another

We will learn more about props in next chapter.

Props are like function arguments, and you send them into the component as attributes.

To pass a color to School component, use an attributes with render() function.


  import React from 'react';
  import ReactDOM from 'react-dom';

  class School extends React.Component {
    render() {
      return <h1>Hi, This is my {this.props.color} School!</h2>;
    }
  }

  ReactDOM.render(<School color="green"/>, document.getElementById('root'));
  

Output :

image

Props in the Constructor

If you are using constructor function in your component, then the props should always be passed to the constructor and also to the React.Component via the super() method.

import React from 'react';
  import ReactDOM from 'react-dom';

  class School extends React.Component {
    constructor(props) {
      super(props);
    }
    render() {
      return <h2>Hi, This is my {this.props.medium} School!</h2>;
    }
  }

  ReactDOM.render(<School medium="English"/>, document.getElementById('root'));

Output :

image

Components in Components

To pass a School component in Attendence component.

import React from 'react';
  import ReactDOM from 'react-dom';

  class School extends React.Component {
    render() {
      return <h2>I am English!</h2>;
    }
  }

  class Attendence  extends React.Component {
    render() {
      return (
        <div>
        <h1>Who Present in class?</h1>
        <School />
        </div>
      );
    }
  }

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

Output :

image

Components in Files

In React, all about re-using the code, We create small package of code that called component. We create a seperate file with .js extension. And put the code inside the file.

We create a file called School.js. And file must start with import as previous and end with export default School;

import React from 'react';

  class School extends React.Component {
    render() {
      return <h1>Hi, this is my School!</h1>;
    }
  }

  export default School;

In React Application inport School.js file. And use the School as a component, it was created.

import React from 'react';
import ReactDOM from 'react-dom';
import School from './School.js';

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

Class Component State

The state is an instance of React Component Class can be defined as an object of a set of observable properties that control the behavior of the component. In other words, the State of a component is an object that holds some information that may change over the lifetime of the component.

React Class components have a built-in state object. we used state earlier in the component constructor section.

Creating the state Object

The state object is initialized in the constructor method.

class School extends React.Component {
    constructor(props) {
      super(props);
    this.state = {medium: "English"};
    }
    render() {
      return (
        <div>
          <h1>My School</h1>
        </div>
      );
    }
  }
  

The state object can contain as many properties :

class School extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        medium: "English",
        board: "CBSE",
        color: "Green",
        year: 1884
      };
    }
    render() {
      return (
        <div>
          <h1>My School</h1>
        </div>
      );
    }
  }  

Using the state Object with render() method

state object anywhere in the component by using the this.state.propertyname syntax

class School extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        medium: "English",
        board: "CBSE",
        color: "Green",
        year: 1884
      };
    }
    render() {
      return (
        <div>
        <h1>My {this.state.medium} ! </h1>
          <p>
            Hi, This is a {this.state.color} color
            {this.state.board} Board School
            from {this.state.year}.
          </p>
        </div>
      );
    }
  }
  

In React Application :

 import React from 'react';
    import ReactDOM from 'react-dom';

    class School extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        medium: "English",
        board: "CBSE",
        color: "Green",
        year: 1884
      };
    }
    render() {
      return (
        <div>
        <h1>My {this.state.medium} ! </h1>
          <p>
            Hi, This is a {this.state.color} color
            {this.state.board} Board School
            from {this.state.year}.
          </p>
        </div>
      );
    }
  }

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

Output :

image

Changing the state Object

To Change the value in state object and component re-render with new value. for changing the state object value to use the this.setState() method.

Use the button with onClick event and that will change the medium property.

import React from 'react';
  import ReactDOM from 'react-dom';

  class School extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        medium: "English",
        board: "CBSE",
        color: "Green",
        year: 1884
      };
    }
    changeBoard = () => {
      this.setState({board: "ICSE"});
    }
    render() {
      return (
        <div>
          <h1>My {this.state.medium}</h1>
          <p>
            Hi, This is a {this.state.color} color 
            {this.state.board} Board School 
            from {this.state.year}.
          </p>
          <button
            type="button"
            onClick={this.changeBoard}
          >Change Board</button>
        </div>
      );
    }
  }

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

Output :

image

After click on button board will be change CBSE to ICSE

image

Arrow Functions

It is the new feature of the ES6 standard. If you need to use arrow functions, it is not necessary to bind any event to 'this.' Here, the scope of 'this' is global and not limited to any calling function. So If you are using Arrow Function, there is no need to bind 'this' inside the constructor.

Arrow functions allow us to write shorter function syntax

let myFunction = (a, b) => a * b;

Normal Function

hello = function() {
  return "Hello World!";
}

With Arrow Function:

hello = () => {
  return "Hello World!";
}

Lifecycle of Components

In React, Each component is monitor and manipulate by three main phases like : Mounting, Updating and Unmounting. React provides callback function to attach functionality in each and every stages of the React life cycle.

image

Mounting

Mounting method means putting the elements into the DOM. These methods are called in the following order when an instance of a component is being created and inserted into the DOM

  • constructor()
  • getDerivedStateFromProps()
  • render()
  • componentDidMount()

- constructor()

constructor() is use to initialize the state() and bind the method in React Application. If you don’t initialize state and you don’t bind methods, you don’t need to implement a constructor for your React component.

constructor() called before it is mounted. When implementing the constructor for a React.Component subclass, you should add super(props) before any other statement. Otherwise, this.props will be undefined in the constructor.

Create a component Medical. constructor method is called by React.

  import React from 'react';
  import ReactDOM from 'react-dom';

  class Medical extends React.Component {
    constructor(props) {
      super(props);
      this.state = {besthospital: "xyz"};
    }
    render() {
      return (
        <h1>The {this.state.besthospital} is the best Hospital !</h1>
      );
    }
  }

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

Output :

image

Basically, constructors are only used for two purposes

  • Initializing local state by assigning an object to this.state
  • Binding event handler methods to an instance.

You should not call setState() in the constructor(). Instead, if your component needs to use local state, assign the initial state to this.state directly in the constructor:

constructor(props) {
  super(props);
  // Don't call this.setState() here!
  this.state = { counter: 0 };
  this.handleClick = this.handleClick.bind(this);
}

- getDerivedStateFromProps()

In React, getDerivedStateFromProps() takes the state as an argument, and returns an object with changes to the state. This is the natural place to set the state object based on the initial props.

The method getDerivedStateFromProps comprises five different words, “Get Derived State From Props”. this method allows a component to update its internal state in response to a change in props. The component state reached in this manner is referred to as a derived state.

The getDerivedStateFromProps() method is called right before rendering the element(s) in the DOM

 import React from 'react';
  import ReactDOM from 'react-dom';

  class Medical extends React.Component {
    constructor(props) {
      super(props);
      this.state = {besthospital: "xyz"};
    }
    static getDerivedStateFromProps(props, state) {
      return {besthospital: props.besthpl };
    }
    render() {
      return (
        <h1>The {this.state.besthospital} is the best Hospital !</h1>
      );
    }
  }

  ReactDOM.render(<Medical  besthpl="abc" />, document.getElementById('root')); 

The example above starts with the best hospital being "xyz", but the getDerivedStateFromProps() method updates the best hospital based on the besthpl attribute.

Output :

image

render()

render() method is required, render() is the method that actually outputs the HTML to the DOM.


  import React from 'react';
  import ReactDOM from 'react-dom';

  class Medical extends React.Component {
    render() {
      return (
        <h1>This is the content for the Medical Hospital..! </h1>
      );
    }
  }

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

Output :

componentDidMount()

In React, componentDidMount() method required, When the component has rendered.

You run this statements that requires, the component is already placed in the DOM

Eg : First, the best hospital "xyz" but But output is Second "abc"

  import React from 'react';
  import ReactDOM from 'react-dom';

  class Medical extends React.Component {
    constructor(props) {
      super(props);
      this.state = {besthospital: "xyz"};
    }
    componentDidMount() {
      setTimeout(() => {
        this.setState({besthospital: "abc"})
      }, 1000)
    }
    render() {
      return (
        <h1>The {this.state.besthospital} is the best Hospital !</h1>
      );
    }
  }

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

Output :

image


Updating

Updating phase in the lifecycle is when a component is updated. An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered

  • getDerivedStateFromProps()
  • shouldComponentUpdate()
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate()

- getDerivedStateFromProps()

In React, getDerivedStateFromProps() use for the update the component. It is the first method that is called, when the component gets updated.

To set the state object based on the initial props is still the natural place.

Create a component Car. There is a button(Change color) that the favorite color to blue, but since the getDerivedStateFromProps() method is called, the favorite color is still rendered as yellow (because the method updates the state with the color from the favcol attribute).

  import React from 'react';
  import ReactDOM from 'react-dom';

  class Car extends React.Component {
    constructor(props) {
      super(props);
      this.state = {favoritecolor: "red"};
    }
    static getDerivedStateFromProps(props, state) {
      return {favoritecolor: props.favcol };
    }
    changeColor = () => {
      this.setState({favoritecolor: "blue"});
    }
    render() {
      return (
        <div>
        <h1>My Favorite Car Color is {this.state.favoritecolor}</h1>
        <button type="button" onClick={this.changeColor}>Change color</button>
        </div>
      );
    }
  }

  ReactDOM.render(<Car favcol="yellow"/>, document.getElementById('root')); 

Output :



- shouldComponentUpdate()

shouldComponentUpdate() method you can return a Boolean(true/false) value.that specifies whether React should continue with the rendering or not. default value is true.

when the shouldComponentUpdate() method returns false


  import React from 'react';
  import ReactDOM from 'react-dom';

  class Car extends React.Component {
    constructor(props) {
      super(props);
      this.state = {favoritecolor: "red"};
    }
    shouldComponentUpdate() {
      return false;
    }
    changeColor = () => {
      this.setState({favoritecolor: "blue"});
    }
    render() {
      return (
        <div>
        <h1>My Favorite Car Color is {this.state.favoritecolor}</h1>
        <button type="button" onClick={this.changeColor}>Change color</button>
        </div>
      );
    }
  }

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

Output :

when the shouldComponentUpdate() method returns true instead :


  import React from 'react';
  import ReactDOM from 'react-dom';

  class Car extends React.Component {
    constructor(props) {
      super(props);
      this.state = {favoritecolor: "red"};
    }
    shouldComponentUpdate() {
      return true;
    }
    changeColor = () => {
      this.setState({favoritecolor: "blue"});
    }
    render() {
      return (
        <div>
        <h1>My Favorite Color is {this.state.favoritecolor}</h1>
        <button type="button" onClick={this.changeColor}>Change color</button>
        </div>
      );
    }
  }

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

Output :


- render()

render() method called when component get updated, and it has to re-reder the HTML to DOM with the new changes.

  import React from 'react';
  import ReactDOM from 'react-dom';

  class Car extends React.Component {
    constructor(props) {
      super(props);
      this.state = {favoritecolor: "red"};
    }
    changeColor = () => {
      this.setState({favoritecolor: "blue"});
    }
    render() {
      return (
        <div>
        <h1>My Favorite Car Color is {this.state.favoritecolor}</h1>
        <button type="button" onClick={this.changeColor}>Change color</button>
        </div>
      );
    }
  }

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

In Out put there is a color change button, On click the color of Car changes red to blue

- getSnapshotBeforeUpdate()

getSnapshotBeforeUpdate() method provide the access to the props and state before update. And also after update, you can check the value that what was the value before update.

Along with this getSnapshotBeforeUpdate() method also you have to include the componentDidUpdate() method, otherwise you will get an error.

This action triggers the update phase, and since this component has a getSnapshotBeforeUpdate() method, this method is executed, and writes a message to the empty color1 element. Then the componentDidUpdate() method is executed and writes a message in the empty color2 element:

  import React from 'react';
  import ReactDOM from 'react-dom';

  class Car extends React.Component {
    constructor(props) {
      super(props);
      this.state = {favoritecolor: "red"};
    }
    componentDidMount() {
      setTimeout(() => {
        this.setState({favoritecolor: "yellow"})
      }, 1000)
    }
    getSnapshotBeforeUpdate(prevProps, prevState) {
      document.getElementById("color1").innerHTML =
      "Before the update, the favorite color was " + prevState.favoritecolor;
    }
    componentDidUpdate() {
      document.getElementById("color2").innerHTML =
      "The updated favorite color is " + this.state.favoritecolor;
    }
    render() {
      return (
        <div>
        <h1>My Favorite Car Color is {this.state.favoritecolor}</h1>
        <div id="color1"></div>
        <div id="color2"></div>
        </div>
      );
    }
  }

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

Output :

When the component is mounting it is rendered with the favorite color "red". a timer changes the state, and after one second, the favorite color becomes "yellow".

- componentDidUpdate()

componentDidUpdate() method is called after the component has been updated in DOM.


  import React from 'react';
  import ReactDOM from 'react-dom';

  class Car extends React.Component {
    constructor(props) {
      super(props);
      this.state = {favoritecolor: "red"};
    }
    componentDidMount() {
      setTimeout(() => {
        this.setState({favoritecolor: "yellow"})
      }, 1000)
    }
    componentDidUpdate() {
      document.getElementById("mycolor").innerHTML =
      "The updated favorite color is " + this.state.favoritecolor;
    }
    render() {
      return (
        <div>
        <h1>My Favorite Car Color is {this.state.favoritecolor}</h1>
        <div id="mycolor"></div>
        </div>
      );
    }
  }

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

Output :

The componentDidUpdate() method is called after the update has been rendered in the DOM:


Unmounting

Unmounting phase in the lifecycle is When the component is removed from the DOM. React has only one built-in method that gets called when a component is unmounted.

  • componentWillUnmount()

componentWillUnmount()

The componentWillUnmount() method called, when you want to remove/delete the component from DOM.

componentWillUnmount() is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount().

You should not call setState() in componentWillUnmount() because the component will never be re-rendered. Once a component instance is unmounted, it will never be mounted again.

 import React from 'react';
  import ReactDOM from 'react-dom';

  class Userlist extends React.Component {
    constructor(props) {
      super(props);
      this.state = {show: true};
    }
    delUser = () => {
      this.setState({show: false});
    }
    render() {
      let myUser;
      if (this.state.show) {
        myUser = <Child />;
      };
      return (
        <div>
        {myUser}
        <button type="button" onClick={this.delUser}>Delete User</button>
        </div>
      );
    }
  }
  class Child extends React.Component {
    componentWillUnmount() {
      alert("The component named User is about to be unmounted.");
    }
    render() {
      return (
      <div>
        <h1>Username : Dinesh</h1>
        <h1>Email : dineshyadav9027@gmail.com</h1>
        <div/>
      );
    }
  }

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

Output :




Error Handling

Error Handling occures when the component is rendering, in a lifecycle method, or in the constructor of any child component.

  • static getDerivedStateFromError()
  • componentDidCatch()

static getDerivedStateFromError()

If an error were to occur in the child component, this method is invoked. The error will be passed as an argument and this method would return a value that will update the state of the class component. This method is useful for rendering a custom fallback UI instead of rendering a broken component

componentDidCatch()

This method receives the error as an argument as well as an object that has information about the error. This method is perfect for logging the error!


To Learn more about React Props in next chapter.