What is the purpose of using super constructor with props argument ?

  • 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.
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like

What is Prop Drilling ?

We pass a prop with another component with the help of all the components that come between, this method is known as prop drilling. Prop drilling is basically a situation…
View Answer

What is React DOM ?

It is an object which exposes a number of top level APIs to interact with the browser DOM. It provides DOM-specific methods that can be used at the top level…
View Answer