I'm learning react from the docs, but not sure what the super()
does in this example. Usually, doesn't it take the arguments that are passed to making a new instance and then calls React.Component's constructor method to incorporate these arguments into the instance? What does it do without any arguments?
class LikeButton extends React.Component {
constructor() {
super();
this.state = {
liked: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({liked: !this.state.liked});
}
render() {
const text = this.state.liked ? 'liked' : 'haven\'t liked';
return (
<div onClick={this.handleClick}>
You {text} this. Click to toggle.
</div>
);
}
}
ReactDOM.render(
<LikeButton />,
document.getElementById('example')
);
In ES6, derived classes have to call super()
if they have a constructor. In react, all components extend from the Component class.
You don't actually need a constructor for every ES6/react class. If no custom constructor is defined, it will use the default constructor. For base classes, it is:
constructor() {}
And for derived classes, the default constructor is:
constructor(...args) {
super(...args);
}
You also need to call super()
before accessing this
, since this
is not initialized until super()
is called.
There are a few reasons to use a custom constructor in react. One is that you can set the initial state within the constructor using this.state = ...
instead of using the getInitialState
lifecycle method.
You can also bind class methods inside the constructor with this.someClassMethod = this.someClassMethod.bind(this)
. It's actually better to bind methods in the constructor since they will only be created once. Otherwise if you call bind
or use arrow functions to bind methods anywhere outside the constructor (like in the render
method), it will actually end up creating a new instance of the function on every render. Read more about that here.
If you want to use this.props
in the constructor, you need to call super
with props as an argument:
constructor(props) {
super(props);
this.state = {count: props.initialCount};
}
If you don't, then this.props
is undefined in the constructor. However, you can still access this.props
anywhere else in the class outside the constructor without needing to do anything with it in the constructor.