Skip to content

Instantly share code, notes, and snippets.

@brownsmith
Last active May 30, 2018
Embed
What would you like to do?
Use of super in React Class constructor
// ES6 class constructors MUST call super if they are subclasses.
// Thus, you have to call super() if you have a constructor.
// A subclass does not have to have a constructor (see #1)
// #1 no need to call super() here as there is no constructor
class MyClass extends React.Component {
render(){
return <div>Hello { this.props.world }</div>;
}
}
// #2 the effects of passing props into your Component
class MyClass extends React.Component{
constructor(props){
super();
console.log(this.props); // this.props is undefined
}
}
// #3 you also need to pass props to super()
class MyClass extends React.Component{
constructor(props){
super(props);
console.log(this.props); // prints out whatever is inside props
}
}
// #4 there is also no need to pass props into the constructor
class MyClass extends React.Component{
render(){
// There is no need to call `super(props)` or have a constructor
// this.props is automatically set for you by React
console.log(this.props); // it works!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment