-1

Why do you need to have the super in the below example? What is it actually grabbing from React.Component that it needs to do to props? Why is super necessary if you're already extending CommentList off of React.Component - wouldn't the props that gets passed in to constructor already be acted upon as if it's passed to React.Component?

class CommentList extends React.Component {
  constructor(props) {
    super(props);
    this.state = { comments: [] }
  } ...
}
mangocaptain
  • 1,435
  • 1
  • 19
  • 31

2 Answers2

1

This is an object oriented programming (OOP) concept regarding inheritance.

Classes can inherit methods and properties from parent classes (in your case CommentList inherits from React.Component [hence the keyword extends])

However, when you name a method with the same name with your new class, the parent class's method gets overwritten.

This idea also applies to contructors (which are methods that run on instantiation).

By nature of OOP, when you declared the constructor on your CommentList, you overwrote the constructor method for React.Component.

Because of this, you need to call super() in order to make sure the parent's constructor also makes use of props. (hence super(props)).

hellojebus
  • 3,267
  • 1
  • 21
  • 23
0
class CommentList extends React.Component {
  constructor(props) {
    console.log(this) // Error
  } 
}

this is not initialized until after super() is called

jshawl
  • 3,315
  • 2
  • 22
  • 34