CodesJava

Easy learning with example program codes

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 (  
<div className="App">  
<h3>Message For You:</h3>  
<input type ="text" value={this.state.data} />  
<button onClick={this.handleEvent}>Click Me</button>  
</div>  
);  
}  
}  
export default App;

Main.js:

import React from 'react';  
import ReactDOM from 'react-dom';  
import App from './App.js';  
ReactDOM.render(<App />, 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 (  
<div className="App">  
<h3>Message For You:</h3>  
<input type ="text" value={this.state.data} />  
<button onClick={this.handleEvent}>Click Me</button>  
</div>  
);  }  }  
export default App;
Please follow and like us:
error









Copyright © 2019 CodesJava DMCA.com Protection Status