React Js — Class Components(Part 2)

Jyoti Karmakar
7 min readJun 26, 2021

Components are the building block of React Js. It is like bricks of building, custom Elements(like div, span) of HTML with content(return), behaviour(methods), data(fields).

Components can be of 2 types

  1. Class component: It is a class of Object orient programming. It has its own state and lifecycle. It must have render() method returning HTML.
  2. Functional component: It is simple javascript functions that accept properties(props) in function and return HTML(JSX). It doesn’t have any state and lifecycle. In our previous example, we have used only functional components.

Class component:

1.1. Basic Class structure:

import { Component } from “react”;class Header extends Component {render() {return (<div style={{background:’#000',color:’#5cc’}}><div> Website Name: Duckbox</div><div>User name: John Doe</div></div>);}}export default Header;

class Header: name of the class is Header.

extends Component: each class should extend “Component” class of react package to make this a special class i.e. component, else it would be like a normal js class.

render(): this a special method, used for returning HTML.

return: return statement of render method that returns HTML

Now we add this component in our MainContainer component.

<div>Hello {props.parentUserName}, welcome to {parentAppName}<Header></Header></div>

Output:

1.2. Lifecycle of Class component:

Lifecycle is a process/steps through which react component is passed to show/render the page and whenever there is any modification in the page(like user does some actions put some inputs, click one button, or change any dropdown) it again pass though some steps of the lifecycle to update the page.

It has 4 stages of life cycle and during each stage some predefided methods are called on a sequence.

Go through this link to have an understanding of the details:
https://hackernoon.com/reactjs-component-lifecycle-methods-a-deep-dive-38275d9d13c0

Here we’ll implement the theory with code examples.

1.2.1. Initialization

In this phase, the React component prepares for the upcoming tough journey, by setting up the initial states and default props, if any.

in this stage constructor method is called to perform this task.

Oh, I forgot! I should give some basic intro of state and property before going any details.

State: The state is used to contain data or information about the component and can change over time. The change in state can happen as a response to user action or system event. In simple, it is the data that is created and controlled by the component. Like the residence address of an employee which can be updated according to his will.

Props: This is the read-only property that is inherited from the parent. This is like the office address of an employee. It is set by the company and even will be updated according to the will of his company. And according to the address he needs to take a bus to reach there he won't have any control but he’ll change his path according to the value set by his company.

Further details: https://www.javatpoint.com/react-state-vs-props

Constructor:

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

Component<any, any>

we are declaring the data types for props(first any)and state(second any).

constructor(props: any) {

Syntax of the constructor method. props is the input data types if props passing from the parent.

super(props);

In JavaScript, super refers to the parent class constructor. (In our example, it points to the React.Component implementation.)

You can’t use this in a constructor, until you’ve called the parent constructor. JavaScript won’t let you:

class Checkbox extends React.Component {
constructor(props) {
// 🔴 Can’t use `this` yet
super(props);
// ✅ Now it’s okay though
this.state = { isOn: true };
}
// ...
}

this.state = {

usersAddress: “Kolkata”

}

Event Binding:
create method changeCompanyAddress

changeCompanyAddress() {this.setState((prevState: any) => ({usersAddress: “London”}));}

this.setState()

we use this method to update state variable.

call changeCompanyAddress()

<button onClick={this.changeCompanyAddress}>Activate Lasers</button>

Now after clicking on the button:

Why?

because “this” is undefined. To use this inside the method we need to bind the event.this.changeCompanyAddress=this.changeCompanyAddress.bind(this);

It's like binding or passing the reference of this to the method.

  1. 2.2. Mounting

After preparing with basic needs, state and props, our React Component is ready to mount in the browser DOM. Mounting is simply like loading the component in the browser.

The methods which get called in this phase are

  • componentWillMount is executed just before the React Component is about to mount on the DOM. All the things that you want to do before a component mounts has to be defined here.
  • render mounts the component onto the browser.
  • componentDidMount this is the hook method which is executed after the component did mount on the DOM. so at this point our DOM is created and we can access the DOM, we should initialize JS libraries like D3 or Jquery which needs to access the DOM.
import { Component } from “react”;class Header extends Component<any, any> {// initialization stageconstructor(props: any) {super(props);this.state = {usersAddress: “Kolkata”}console.log(“Inside constructor, user is currently at: Kolkata, officical address:”, this.state.usersAddress)this.changeCompanyAddress = this.changeCompanyAddress.bind(this);}//mounting stagecomponentWillMount() {this.setState(() => ({usersAddress: “Delhi”}));console.log(“Inside componentWillMount, user is currently at: Delhi, officical address:”, this.state.usersAddress)}render() {console.log(“Inside render, user can not change its city, just updating official address by setting value from setstate.\n now:”, this.state.usersAddress)return (<div style={{ background: ‘#000’, color: ‘#5cc’ }}><div> Website Name: Duckbox, Company Address: {this.props.companyAddress}</div><div>User name: John Doe, User Address: {this.state.usersAddress}</div><button onClick={this.changeCompanyAddress}>Change Company Address</button></div>);}componentDidMount() {this.setState(() => ({usersAddress: “Dubai”}));console.log(“Inside componentDidMount, user is currently at: Dubai, officical address:”, this.state.usersAddress)}// custom methodschangeCompanyAddress() {this.setState(() => ({usersAddress: “London”}));}}export default Header;

N.B. though setState method is calling state value is not updating immediately. It is only updating when render method is executing. And render method would be called each time when the value inside “this” is changed.
So, you can not change value inside “this” inside render method(else it would become an infinity loop)

3) Update

This phase starts when the react component has taken birth on the browser and grows by receiving new updates. The component can be updated by two ways, sending new props or updating the state.

shouldComponentUpdate tells the React that when the component receives new props or state is being updated, should React re-render or it can skip rendering? By default, this method return true.

componentWillUpdate is executed only after the shouldComponentUpdate returns true. This method is only used to do the preparation for the upcoming render, similar to componentWillMount or constructor.

  • render And then the component gets rendered.
  • componentDidUpdate is executed when the new updated component has been updated in the DOM. This method is used to re trigger the third party libraries used to make sure these libraries also update and reload themselves.

4) Unmounting

In this phase, the component is not needed and the component will get unmounted from the DOM. The method which is called in this phase.

componentWillUnmount This method is the last method in the lifecycle. This is executed just before the component gets removed from the DOM.

import { Component } from “react”;class Header extends Component<any, any> {// initialization stageconstructor(props: any) {super(props);this.state = {usersAddress: “Kolkata”}console.log(“Inside constructor, user is currently at: Kolkata, officical address:”, this.state.usersAddress)this.changeCompanyAddress = this.changeCompanyAddress.bind(this);}//mounting stagecomponentWillMount() {this.setState(() => ({usersAddress: “Delhi”}));console.log(“Inside componentWillMount, user is currently at: Delhi, officical address:”, this.state.usersAddress)}render() {console.log(“Inside render, user can not change its city, just updating official address by setting value from setstate.\n now:”, this.state.usersAddress)return (<div style={{ background: ‘#000’, color: ‘#5cc’ }}><div> Website Name: Duckbox, Company Address: {this.props.companyAddress}</div><div>User name: John Doe, User Address: {this.state.usersAddress}</div><button onClick={this.changeCompanyAddress}>Change Company Address</button><a href=”https://www.google.com/">go to google</a></div>);}componentDidMount() {this.setState(() => ({usersAddress: “Kabul”}));console.log(“Inside componentDidMount, user is currently at: Kabul, officical address:”, this.state.usersAddress)}// updateshouldComponentUpdate(nextProps: any, nextState: any) {console.log(“Inside shouldComponentUpdate,there is some update happen props or state,deciding wheater to update or not”);console.log(“User don’t want to show his friends that he visited Kabul, so if the current city is Kabul he wont render that”);console.log(“current props: “, this.props, “ updated props: “, nextProps);console.log(“current state: “, this.state, “ updated state: “, nextState);if (nextState.usersAddress == “Kabul”) {return false;}else {return true;}}componentWillUpdate() {console.log(“Inside componentDidUpdate, user is currently at: “, this.state.usersAddress, “ officical address:”, this.state.usersAddress)console.log(“We should not change location now,else value would again change and the method would again call in infinity loop: “);}componentDidUpdate() {console.log(“Inside componentDidUpdate, user is currently at: “, this.state.usersAddress, “ officical address:”, this.state.usersAddress)console.log(“We should not change location now,else value would again change and the method would again call in infinity loop: “);}// unmountcomponentWillUnmount() {console.log(“Inside componentWillUnmount, leaving the universe”);}// custom methodschangeCompanyAddress() {this.setState(() => ({usersAddress: “London”}));}}export default Header;

--

--