• This method has been known as, a child class constructor cannot create use of this reference until super() .
  • The same applies for ES6 sub-classes as well.
  • The main reason of passing props parameter to super() call is to access this.props in your child constructors.
  • The super() is a requirement, while implementing the constructor() function inside a React component.
  • For example, super(props) would call the React.
  • Component constructor passing in props as the argument.

For example in Passing props

class MyComponent extends React.Component {
constructor(props) {
super(props)

console.log(this.props) // prints { name: 'bharath', age: 23}
}
}

 

For example in Not passing props

class MyComponent extends React.Component {
constructor(props) {
super()

console.log(this.props) // prints undefined

// but props parameter is still available
console.log(props) // prints { name: ' bharath ', age: 23 }
}

render() {
// no difference outside constructor
console.log(this.props) // prints { name: ' bharath ', age: 23 }
}
}
  • In The above code snippets shows that this.props is different only within the constructor.
  • It would be the same outside the constructor.

Categorized in: