Constructor in ReactJS

React Constructor
The method used to initialize an object’s state and which is automatically called during the creation of an object in a class is known as a constructor in ReactJS. It is called before the component is mounted in ReactJS, but the constructor is not necessary to be present in every component. However, calling super() inside a constructor is necessary for ReactJS.

Syntax:

Constructor(props){  
super(props);  
}  

Example:
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 (  

Message For You:

); } } 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:

Uses of React constructors:

To initialize the local state of the component:

class App extends Component {  
constructor(props){  
this.state = {  
inputTextValue: 'final value',  
};  
}  
}  

To use ‘this’ inside constructor:

class App extends Component {  
constructor(props) {  
super();  
super(props);  
}  
}  

To initialize third-party libraries:

class App extends Component {  
constructor(props) {  
this.myjournal = new MyJournalLibrary();  
this.journal = new MyJournalLibrary(props.environment);  
}  
}  

Binding some context(this) when a class method is needed to be passed in props to children:

class App extends Component {  
constructor(props) {  
this.handleFunction = this.handleFunction.bind(this);  
}  
}  

Arrow Functions:
When using the Arrow Function, binding ‘this’ inside the constructor is not required.

Example:

import React, { Component } from 'react';  
class App extends Component {  
constructor(props){  
super(props);  
this.state = {  
data: 'Hello World'  
}  
}  
handleEvent = () => {  
console.log(this.props);  
}  
render() {  
return (  

Message For You:

); } } export default App;