Blog Details

img
Data Science

what Is constructor needed in ReactJS

Spoke Right / 14 Nov, 2023

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:

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

Click Me
); } } export default App;

0 comments

Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /usr/local/lib/php/extensions/no-debug-non-zts-20210902/imagick.so (/usr/local/lib/php/extensions/no-debug-non-zts-20210902/imagick.so: cannot open shared object file: No such file or directory), /usr/local/lib/php/extensions/no-debug-non-zts-20210902/imagick.so.so (/usr/local/lib/php/extensions/no-debug-non-zts-20210902/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0