19

I am not great with JS and playing around with React.

The React docs located here state the following:

When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs.

My question is HOW does this actually work? What is super() doing that magically enables this.props within my constructor?

Billy Blob Snortin
  • 1,101
  • 3
  • 11
  • 17

1 Answers1

26

In the documentation that you have mentioned. It is coded in ES6 standard of javascript.

So this statement

class Greeting extends React.Component

It means Greeting is inherting from React.Component, by calling super, you are actually calling the parent element with props parameter,

if you intend on using this.props inside the constructor, you have to call super(props)

Hope these links are helpful.

Johannes Fahrenkrug
  • 42,912
  • 19
  • 126
  • 165
Geeky
  • 7,420
  • 2
  • 24
  • 50
  • why would anyone want to use `this.props` instead of just `props`, inside the constructor? – Magne Apr 26 '18 at 11:33
  • 1
    nvm, I realise `this.props` is necessary to use instead of `props` if you want to modify the props themselves. – Magne Apr 26 '18 at 11:36
  • @Magne note that you shouldn't modify props as they are [supposed to be immutable](https://reactjs.org/docs/components-and-props.html#props-are-read-only) – KubaJastrz May 22 '18 at 13:20
  • @KubaJastrz yeah, you're correct, but I was merely talking about setting `this.props = props` in the constructor, which is the only "exception" to that rule. – Magne May 23 '18 at 15:17