1

I'getting undefined this error in the constructor. Let me know what is the reason behind this. I read from the sources either compiler automatically creates the constructor and available this reference or need to manually add the constructor with super() as the first statement.

class A extends Component {
  constructor() {
    // this undefined error
    console.log('construtor');
    this.state = {name: ''}        
  }
}

2 Answers 2

5

The reason why this cannot be allowed before super() is because this is uninitialized if super() is not called. However even if we are not using this we need a super() inside a constructor because ES6 class constructors MUST call super if they are subclasses. Thus, you have to call super() as long as you have a constructor. (But a subclass does not have to have a constructor).

sending props in super is not mandatory. If you do not want to use this.props then you can simply call super().

class A extends React.Component {   
    constructor(props) {
    super(props);
    console.log('construtor');
    this.state = {name: ''}           
    } 
}
Sign up to request clarification or add additional context in comments.

Comments

2

The subclasses must have super in constructor for initializing purpose. Access of 'this' can't be allowed without super().

class A extends React.Component {
      constructor(props) {
           super(props);
           console.log('construtor');
           this.state = { name: ''}
      }
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.