in React JS by
Q:

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

1 Answer

0 votes
by

A child class constructor cannot make use of this reference until super() method has been called. 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.

Passing props:

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

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

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: 'John', age: 42 }
  }

  render() {
    // no difference outside constructor
    console.log(this.props) // prints { name: 'John', age: 42 }
  }
}

The above code snippets reveals that this.props is different only within the constructor. It would be the same outside the constructor.

Click here to read more about React JS
Click here to read more about Insurance

Related questions

0 votes
asked Jul 2, 2019 in React JS by Venkatshastri
0 votes
asked Jun 19, 2020 in React JS by JackTerrance
0 votes
asked Jul 2, 2019 in React JS by Venkatshastri
0 votes
asked Jul 2, 2019 in React JS by Venkatshastri
0 votes
0 votes
asked Jul 2, 2019 in React JS by Venkatshastri
...