×

React Constructors

What is constructor?

The constructor is a method that is used for initializing the state of the object in the class. It calls automatically during the creation of an object in the class.

The concept of the constructor is also the same in the React. The constructor in a React component is called before the component is mounted. When you implement the constructor for a React component, you have to call the super(pros) method before any other statement. If you are not calling super(pros) method, this.props will be undefined in the constructor and can lead to bugs.

Syntax

Constructor(props){
super(props);
}

In React, there are mainly two purposes for using the constructors:

  1. It is used for the initialization of the local state of the component by assigning an object to this.state.
  2. It is used to bind the event handler method, which occurs in your component.

If you are not initializing the state and not binding the methods for your React component, then it does not require implementing a constructor for a React component.

The setState() method cannot call directly in the constructor(). If the component requires to use local state, you have to use 'this.state’ to assign the initial state in the constructor. The only constructor uses this.state for assigning the initial state, and all other methods require to use set.state() method.

Example:

The example given below illustrates the concept of the constructor:

App.js

import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: 'Hello World'
    };
    this.handleEvent = this.handleEvent.bind(this);
  }

  handleEvent() {
    console.log(this.props);
  }

  render() {
    return (
      <div>
        <h2>Example of React Constructor</h2>
        <p>{this.state.data}</p>
        <button onClick={this.handleEvent}>Please Click</button>
      </div>
    );
  }
}

export default App;

Main.js

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import App from './App.js'; 
ReactDOM.render(, document.getElementById('app'));  

Output:

Example of React Constructor

Arrow Functions

It is the new feature in the ES6 standard. If you apply arrow functions, it is not mandatory to bind any event to 'this' and also no need to bind 'this' inside the constructor.

Example:

In the above example, we have used bind(), but by using arrow function, we don't need it anymore. The following example is illustrating how to use arrow function in the program.

import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: 'Hello World'
    };
    this.handleEvent = this.handleEvent.bind(this);
  }

  handleEvent = () => {
    console.log(this.props);
  };

  render() {
    return (
      <div>
        <h2>Example of React Constructor</h2>
        <p>{this.state.data}</p>
        <button onClick={this.handleEvent}>Please Click</button>
      </div>
    );
  }
}

export default App;

Output:

React Contructor

There are some ways in which we can use the constructor that are as follows:

1. Use of 'this' inside the constructor

class App extends Component {
constructor(props) {
// when you use 'this' in constructor, super() needs to be called first
super();
// it means, when you want to use 'this.props' in constructor, call it as below
super(props);
}
} 

2. Initializing third-party libraries

class App extends Component { 
constructor(props) { 
this.myProgram = new MyProgramLibrary(); 
//Here, you can access props without using 'this' 
this.Program2 = new MyProgramLibrary(props.environment); 
} 
}  

3. The constructor is used to initialize the state.

class App extends Component { 
constructor(props){ 
// here, it is setting initial value for 'inputTextValue' 
this.state = { 
inputTextValue: 'initial value', 
}; 
} 
}  

4. Binding the context (this) when you require a class method to be passed in props to children.

class App extends Component {
  constructor(props) {
    // When you need to 'bind' context to a function
    this.handleFunction = this.handleFunction.bind(this);
  }
}

There are some questions related to constructors are as follows:

5. Is it mandatory to have a constructor in every component?

No, it does require having a constructor in every component. If there is not a complex component, it simply returns a code.

classAppextendsComponent{ render(){ return(

Name:{this.props.name}

); } }

6. Is it compulsory to call super() inside a constructor?

Yes, it is always required to call super() inside a constructor. If you have to set a property or access 'this' inside the constructor in your component, you require to call super().

For example:

Without using super(props)

The program given below will show you an error:

ReferenceError: Must call the super constructor in derived class before accessing 'this' or returning from derived constructor.

This happens because there is not any use of super(props).

import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props);
    this.fName = {
      name: 'Nikhil',
      age: 20,
      class: 'Fifth',
      subject: 'Computers'
    };
  }

  render() {
    return (
      <div>
        <h2>Name: {this.fName.name}</h2>
        <p>Age: {this.fName.age}</p>
        <p>Class: {this.fName.class}</p>
        <p>Subject: {this.fName.subject}</p>
      </div>
    );
  }
}

export default App;

With using super(props)

After inserting super(props), you will get your required output.

import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props);
    this.fName = {
      name: 'Nikhil',
      age: 20,
      class: 'Fifth',
      subject: 'Computers'
    };
  }

  render() {
    return (
      <div>
        <h2>Name: {this.fName.name}</h2>
        <p>Age: {this.fName.age}</p>
        <p>Class: {this.fName.class}</p>
        <p>Subject: {this.fName.subject}</p>
      </div>
    );
  }
}

export default App;

Output:

React Constructor

Related Topics

React Bootstrap

React Bootstrap React has a widely used JavaScript framework for creating web applications, and Bootstrap has become the most popular CSS framework. Single-page apps have become popular from the last few...

9 minutes read.

React Native vs ReactJS

Difference between React Native and ReactJS React Native React Native is also an open-source JavaScript framework that is used for the development of a mobile application for iOS Android and Windows. It...

6 minutes read.

React Fragments

React Fragments The fragments in React are introduced from the 16.2 and above versions. Fragments allow you to group a list of child elements without adding any extra node in the DOM. In React,...

2 minutes read.

React Props

React Props A prop is an abbreviation of ‘properties.' State and props are mainly different from each other because props are immutable. Props are the read-only components. It is the object that stores the attribute...

3 minutes read.

React CSS

What is React CSS React CSS is used to provide the style to the React applications. The style attribute adds dynamically-computed styles at render time, and it is one of the most used...

5 minutes read.

React Animation

React Animation The animation is a procedure in which an image is manipulated to appear as a moving image. It is widely used to create an interactive web application. In React, we have to...

4 minutes read.

ReactJS Tutorial

ReactJS Introduction React Tutorial helps you to understand the basic and some advanced concepts of ReactJS. As of now, it is the essential front-end library that is developed by a...

3 minutes read.

Difference between Controlled and Uncontrolled component in ReactJs

Controlled Component In the controlled component, the input of the form element is handled by the component rather than the DOM. Controlled components have the functions that govern the data, which...

2 minutes read.

React Error Boundaries

React Error Boundaries In the past, the errors of JavaScript within the components were used to corrupt the internal state of react and cause it to emit the cryptic errors on the next...

3 minutes read.

React Router

What is React Router? Routing is a process by which a user can direct to different pages based on their actions and requests. ReactJS router is generally used to develop single...

10 minutes read.

Features of ReactJS

ReactJS Features As of now, within the developers, ReactJS is gaining much popularity as the best JavaScript framework. It is crucial for the front-end ecosystem. There are some of the crucial features of ReactJS that are...

2 minutes read.

React Environment Setup Step by Step

React Environment Setup This section will provide you the information about how to set up an environment for the successful development of ReactJS application: Pre-Requisite for ReactJS NodeJS and NPMReact and React DOMWebpackBabel There are two...

5 minutes read.

React Portals

React Portals React portals were introduced by React 16.0 in September 2017. It gives you a way to render the element outside of the component hierarchy, i.e., within a separate component. Before React 16.0, it...

3 minutes read.

React Map

React Map The map() is the standard function of JavaScript, which can be called at any array. The map() method is used for traversing and displaying a list of the similar objects of...

2 minutes read.

React Higher-Order Components

React Higher-Order Components In short form, Higher-Order Components are represented as HOC. The Higher-order component is an advanced technique to use component logic. HOC is a function that takes the component and returns the new...

2 minutes read.

React Constructors

What is constructor? The constructor is a method that is used for initializing the state of the object in the class. It calls automatically during the creation of an object in...

4 minutes read.

React Refs

React Refs The word ‘Refs’ is an abbreviation of ‘References’ in React. It is as similar as Keys in React. Refs are a function in React which is used for accessing the DOM element and...

7 minutes read.

React Component API

React Component API It is a top-level API. It provides reusability to the code in the application and makes it completely individual. It has several methods for: Creating Elements.Transforming Elements.Fragments. Now, we are explaining the three...

2 minutes read.

Pros and Cons of ReactJS

Pros and Cons of ReactJS There are various advantages, and disadvantages of ReactJS are as follows: Benefits of ReactJS 1. Easy to Learn and Use: ReactJS is very easy to use and learn. It has a good...

3 minutes read.

React Component Life-Cycle

React Component Life-Cycle In ReactJS, the creation process of every component includes several lifecycle methods. These methods, together stated as component's lifecycle. Four phases of the component's life cycle are as...

4 minutes read.