javascripting
javascripting

Reputation: 1153

React - Why can I use React's methods without calling super?

I wonder, how is it possible that a component can use reacts methods, such as render, componentDidMount etc. if calling the constructor with super is not mandatory? Shouldn't it be that a component inherits the methods of its Parent class (which is React since I'm extending it) and calling super to use them? Thanks!

Upvotes: 1

Views: 2096

Answers (2)

Estus Flask
Estus Flask

Reputation: 222498

The question isn't specific enough about what calling super refers to, while it can mean two different things.

super() refers to parent constructor call. It is necessary only in child constructor. It is mandatory in child constructor once it's used, this is required by ES6 specification:

class Parent extends Component {
  constructor(props) {
    // if no super() is called, it's invalid ES6 class 
  }

  render() {...}
}

But the constructor itself isn't mandatory (so-called implicit constructor):

class Parent extends Component {
  state = {};

  // is a shortcut for:
  /*
  constructor(props) {
    super(props);
    this.state = {}
  }
  */

  render() {...};
}

super.method refers to method property on parent class prototype. It can be used in child constructor and prototype methods. Its use is optional.

Child class can override a method entirely without using respective super method:

class Parent extends Component {
  render () { return 'foo'; }
}

class Child extends Parent {
  render () { return 'bar'; }
}

Or augment its functionality:

class AnotherChild extends Parent {
  render () { return <h1>{super.render()}</h1>; }
}

Upvotes: 3

ThatBrianDude
ThatBrianDude

Reputation: 3190

super() will populate the base class (in your case React.Component) constructor with whatever you pass it.

Extending a class will inherit properties and methods.

You may absolutely extend a class without using its constructor. Thus never calling super().

As for super() and react, if you are making use of props you will need to pass them down to the base class.

Upvotes: 0

Related Questions