ReactJS Constructor Tutorial Example is today’s leading topic. In a ReactJS Initial State Tutorial, we have seen that one use of constructor is to define the initial state of the component, which is very useful for any react.js application. We can also bind any event that occurs in our component in the constructor like the following.
constructor(props){
super(props);
this.handleEvent = this.handleEvent.bind(this);
}
In above’s example, 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 parent. Let me take one example to simplify this explanation.
ReactJS Constructor Tutorial
Example #1
// 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 call the function called handleEvent(). However, when you see in the browser, the application gets a crash, and it has shown me like this.

So, here the problem is that this is no longer work as a global class object, it is pointing all the properties inside that called function. So, we need to make this as a global application pointer on which we can call the props and state methods. To overcome the problem, write the following line in the constructor.
// 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;
Bind() function will get the job done because, at the starting point of our component, we are binding this object to the global element and it has all the props and state.
Example #2
We can also use arrow function to get rid of bind function like following way.
// 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, which is the new feature of the ES6 standard is correctly set the context of this to parent and not that particular function. Both will work same.
So, we can achieve two purposes with the constructor function.
- Set the initial state of the component
- Point the global context of this keyword.
So, our ReactJS Constructor Tutorial is finally over.
0 comments:
Post a Comment
Note: only a member of this blog may post a comment.