Many time we send props in the constructor but we never use this.props anywhere in the constructor so why do need to pass that and when do need to do that.
class App extends React.Component {
constructor(props) {
super(props); // When do we need to send props to the constructor
this.state = {
data: 'Initial data...'
}
this.updateState = this.updateState.bind(this);
};
updateState(e) {
this.setState({data: e.target.value});
}
render() {
return (
<div>
<input type = "text" value = {this.state.data}
onChange = {this.updateState} />
<h4>{this.state.data}</h4>
</div>
);
}
}
So to ensure that the React. Component 's constructor() function gets called, we call super(props) . super(props) is a reference to the parents constructor() function, that's all it is. We have to add super(props) every single time we define a constructor() function inside a class-based component.
Using super constructor with props arguments basically allows accessing this. props in a Constructor function. Let us create a React project and then we will create a UI to showcase the above purpose. Users will be able to see the application of the super constructor with props argument.
It turns out that React also assigns props on the instance right after calling your constructor: // Inside React const instance = new YourComponent(props); instance. props = props; So even if you forget to pass props to super() , React would still set them right afterwards.
The super() is used inside the constructor for the purpose to get access to this keyword inside our constructor. With this let's try to understand super() first. Super is a keyword in JavaScript and is used to call super or parent class in the hierarchy. React class extends React Component with ES6 syntax.
Props aren't actually needed by the React.Component
constructor. You can write this code and everything works just fine:
constructor() {
super();
this.state = {
data: 'Initial data...'
};
this.updateState = this.updateState.bind(this);
};
This is because the constructor path is not actually where your props get assigned in the standard React life cycle. React.Component
does not actually use props and only sets this.props
in case your constructor needs to use it. But usually you shouldn't be using props
in your constructor anyway because using props to initialize your state is an anti-pattern
If you've configured babel, you don't even need a constructor for stuff like this:
class MyComponent extends React.Component {
state = { data: "initial data" };
updateState = (arg1, arg2) => { ... };
// instead of:
// updateState(arg1, arg2) { ... }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With