Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React, why use super(props) inside of ES6 class constructor? [duplicate]

I realize the super keyword can be used to call functions in a parent component. However, I'm not totally clear why you would use the super keyword in the example below - just passing it whatever props are being passed to the constructor.

Can someone please shed some light on the various reasons for using the super keyword in an ES6 class constructor, in react?

  constructor(props) {
    super(props);

    this.state = {
      course: Object.assign({}, this.props.course),
      errors: {   }
    };

    this.updateCourseState = this.updateCourseState.bind(this);
  }
like image 607
malexanders Avatar asked Jun 17 '16 22:06

malexanders


People also ask

What is the purpose of super props used in constructor of a React class component?

super() is used to call the parent constructor. super(props) would pass props to the parent constructor. From your example, super(props) would call the React. Component constructor passing in props as the argument.

Why do we call super props?

When we call this super(props), we are basically calling the constructor of React. Component. So we can say that super() is a reference to the parent class constructor i.e. React. Component in the above example, which is also the base class for Person component.

Why do constructor props React?

In React, the constructor is called during component creation and before mounting. If you want to implement the constructor for a React component, call the super(props) method before any other statement. Otherwise, this. props will be undefined in the constructor and create bugs.


1 Answers

super allows you to access the constructor method of the parent class. The only reason to include props is to access this.props inside of your constructor.

What's the difference between "super()" and "super(props)" in React when using es6 classes?

like image 185
jmancherje Avatar answered Nov 13 '22 07:11

jmancherje