gotchajavascriptreactCritical
What's the difference between "super()" and "super(props)" in React when using es6 classes?
Viewed 0 times
whatsuperpropswhentheandes6classesreactdifference
Problem
When is it important to pass
props to super(), and why?class MyComponent extends React.Component {
constructor(props) {
super(); // or super(props) ?
}
}Solution
There is only one reason when one needs to pass
When you want to access
Passing:
Not passing:
Note that passing or not passing
This is explicitly said in one Sophie Alpert's answer to a similar question.
The documentation—State and Lifecycle, Adding Local State to a Class, point 2—recommends:
Class components should always call the base constructor with
However, no reason is provided. We can speculate it is either because of subclassing or for future compatibility.
(Thanks @MattBrowne for the link)
props to super():When you want to access
this.props in constructor.Passing:
class MyComponent extends React.Component {
constructor(props) {
super(props)
console.log(this.props)
// -> { icon: 'home', … }
}
}Not passing:
class MyComponent extends React.Component {
constructor(props) {
super()
console.log(this.props)
// -> undefined
// Props parameter is still available
console.log(props)
// -> { icon: 'home', … }
}
render() {
// No difference outside constructor
console.log(this.props)
// -> { icon: 'home', … }
}
}Note that passing or not passing
props to super has no effect on later uses of this.props outside constructor. That is render, shouldComponentUpdate, or event handlers always have access to it.This is explicitly said in one Sophie Alpert's answer to a similar question.
The documentation—State and Lifecycle, Adding Local State to a Class, point 2—recommends:
Class components should always call the base constructor with
props.However, no reason is provided. We can speculate it is either because of subclassing or for future compatibility.
(Thanks @MattBrowne for the link)
Code Snippets
class MyComponent extends React.Component {
constructor(props) {
super(props)
console.log(this.props)
// -> { icon: 'home', … }
}
}class MyComponent extends React.Component {
constructor(props) {
super()
console.log(this.props)
// -> undefined
// Props parameter is still available
console.log(props)
// -> { icon: 'home', … }
}
render() {
// No difference outside constructor
console.log(this.props)
// -> { icon: 'home', … }
}
}Context
Stack Overflow Q#30571875, score: 839
Revisions (0)
No revisions yet.