40

I'm learning react from the docs, but not sure what the super() does in this example. Usually, doesn't it take the arguments that are passed to making a new instance and then calls React.Component's constructor method to incorporate these arguments into the instance? What does it do without any arguments?

class LikeButton extends React.Component {
  constructor() {
    super();
    this.state = {
      liked: false
    };
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.setState({liked: !this.state.liked});
  }
  render() {
    const text = this.state.liked ? 'liked' : 'haven\'t liked';
    return (
      <div onClick={this.handleClick}>
        You {text} this. Click to toggle.
      </div>
    );
  }
}

ReactDOM.render(
  <LikeButton />,
  document.getElementById('example')
);
4
  • 4
    super(), in most class based languages means call the parent's constructor. So it would be calling React.Component's constructor.
    – Keith
    Oct 2, 2016 at 23:57
  • Does the super constructor have default arguments (implicit or otherwise) that would allow zero arguments to make sense? This seems like it could be solved by looking at the source code. Oct 2, 2016 at 23:58
  • React.Component constructor takes one argument facebook.github.io/react/docs/…
    – Dionys
    Oct 3, 2016 at 0:08
  • I believe this answers your question: stackoverflow.com/a/34995257/1517783 Apr 6, 2017 at 8:13

2 Answers 2

56

In ES6, derived classes have to call super() if they have a constructor. In react, all components extend from the Component class.

You don't actually need a constructor for every ES6/react class. If no custom constructor is defined, it will use the default constructor. For base classes, it is:

constructor() {}

And for derived classes, the default constructor is:

constructor(...args) {
  super(...args);
}

You also need to call super() before accessing this, since this is not initialized until super() is called.

There are a few reasons to use a custom constructor in react. One is that you can set the initial state within the constructor using this.state = ... instead of using the getInitialState lifecycle method.

You can also bind class methods inside the constructor with this.someClassMethod = this.someClassMethod.bind(this). It's actually better to bind methods in the constructor since they will only be created once. Otherwise if you call bind or use arrow functions to bind methods anywhere outside the constructor (like in the render method), it will actually end up creating a new instance of the function on every render. Read more about that here.

If you want to use this.props in the constructor, you need to call super with props as an argument:

constructor(props) {
  super(props);
  this.state = {count: props.initialCount};
}

If you don't, then this.props is undefined in the constructor. However, you can still access this.props anywhere else in the class outside the constructor without needing to do anything with it in the constructor.

28

The super keyword in JavaScript is used in order to call the methods of the parent class. By itself, super() is used within a constructor function to call the parent constructor function. For example:

class Animal {
  
  constructor(age) {
    console.log('Animal being made');
    this.age = age;
  }
  
  returnAge() {
    return this.age;
  }
  
}

class Dog extends Animal {

  constructor (age){
    super(age);
  }
  
  logAgeDog () {
    console.log(`This dog is: ${ super.returnAge()} years old`);
  }
  
}

const dog = new Dog(5);


console.log(dog);

dog.logAgeDog();

In this example we have a Dog class which extends an Animal class. The Dog class uses the super keyword twice. The first occurence is in the constructor, when super() is used in the constructor it will call the parent class constructor. Therefore we have to give the age property as an argument to it. Now the Dog successfully has an age property.

We can also use super outside of the constructor in order to access the parent's 'class' (i.e. prototype) properties and methods. We use this in the logAgeDog function located in the Dog class. We use the following code:

super.returnAge();

You should read this as:

Animal.returnAge();     // superClass.returnAge()

Why do I need this in React?

You need the super() keyword in React only when implementing a constructor. You have to do the following:

constructor(props) {
  super(props);
  // Don't call this.setState() here!
}

the parent class which is named Component needs to do some initialization on its own in order for React to work fine. If you implement a constructor without a super(props) call this.props in Component will be undefined which can lead to bugs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.