Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is super(props) doing for my React component?

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?

like image 338
Billy Blob Snortin Avatar asked Jan 24 '17 20:01

Billy Blob Snortin


1 Answers

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.

like image 142
Geeky Avatar answered Sep 25 '22 14:09

Geeky