React.js constructor() Method

React constructor() method is “used to initialize an object’s state in a class.” It is automatically called during the creation of an object in a class. The constructor can bind event handlers to the component and initialize the component’s local state.

The constructor() method is fired before the component is mounted, and, like most things in React, you should follow a few rules when using them.

Syntax

 constructor(props){
   super(props);
   this.handleEvent = this.handleEvent.bind(this);
 }

In the snippet, the event will fire after the user has clicked the button or keyup, blur, or any other event, and then we need to set up the context to its parent and not the child context, so we are binding this to the parent. Let me take one example to simplify this explanation.

Example 1: How to Use constructor() Method in React.js

// App.js

import React, { Component } from 'react';

class App extends Component {
  constructor(props){
    super(props);
  }
  handleEvent(){
    console.log(this.props);
  }
 render() {
   return (
      <div className="App">
        <button onClick={this.handleEvent}>Please Click</button>
      </div>
   );
  }
}

export default App;

In this example, I have taken one button, and when the user clicks the button, that triggered event calls the function called handleEvent(). However, when you see it in the browser, the application gets a crash, and it has shown me this.

this context error

The problem is that this no longer works as a  global class object; it points to all the properties inside that function. So, we need to make this a global application pointer on which we can call the props and state methods.

Fixing the error

// App.js

import React, { Component } from 'react';

class App extends Component {
  constructor(props){
    super(props);
    this.handleEvent = this.handleEvent.bind(this);
  }
  handleEvent(){
    console.log(this.props);
  } 
 render() {
   return (
     <div className="App">
       <button onClick={this.handleEvent}>Please Click</button>
     </div>
   );
  }
}

export default App;

The bind() function will get the job done because, at the starting point of our component, we bind this object to the global element, and it has all the props and state.

Example 2

// App.js

import React, { Component } from 'react';

class App extends Component {
  constructor(props){
    super(props);
  }
  handleEvent = () => {
    console.log(this.props);
  }
 render() {
   return (
     <div className="App">
       <button onClick={this.handleEvent}>Please Click</button>
     </div>
   );
  }
}

export default App;

Here, arrow functions, the new feature of the ES6 standard, correctly set the context of this to parent and not that particular function. So both will work the same.

That’s it.

1 thought on “React.js constructor() Method”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.