I've seen many code snippets such as HelloWorld
, where props
is passed to super()
.
What is the reason to do that when this.props
is not accessed in the constructor?
class HelloWorld extends Component {
constructor(props) {
super(props);
this.state = { message: 'Hi' };
this.logMessage = this.logMessage.bind(this);
}
logMessage() {
console.log(this.state.message);
}
render() {
return (
<input type="button" value="Log" onClick={this.logMessage} />
);
}
}
The constructor for a React component is called before it is mounted. When implementing the constructor for a React component subclass, you should call super(props)
before any other statement.
Otherwise, this.props
will be undefined in the constructor, which can lead to bugs.
Read Here for more details.
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