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


When is it important to pass props to super(), and why?

class MyComponent extends React.Component {
  constructor(props) {
    super(); // or super(props) ?


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.

More information on super: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super

By : kspence

When you pass props to super, the this the props get assigned to this. Take a look at the following scenario:

constructor(props) {
    console.log(this.props) //undefined

How ever when you do :

constructor(props) {
    console.log(this.props) //props will get logged.

Here is the fiddle I've made: https://jsfiddle.net/beshanoe/zpxbLw4j/1/. It shows that props are assigned not in the constructor by default. As I understand they are assinged in the method React.createElement. Hence super(props) should be called only when the superclass's constructor manually assings props to this.props. If you just extend the React.Component calling super(props) will do nothing with props. Maybe It will be changed in the next versions of React.

By : beshanoe

This video can help you solving your question :)
By: admin