Last active
May 30, 2018 13:39
-
-
Save brownsmith/3a7126d602265ca64d12cbfc1969cdae to your computer and use it in GitHub Desktop.
Use of super in React Class constructor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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