Shubham
Shubham

Reputation: 1191

ReactJS constructor 'this' undefined error

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: ''}        
  }
}

Upvotes: 1

Views: 1280

Answers (2)

Elumalai Kaliyaperumal
Elumalai Kaliyaperumal

Reputation: 1520

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: ''}
      }
}

Upvotes: 2

Akash Bhandwalkar
Akash Bhandwalkar

Reputation: 901

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: ''}           
    } 
}

Upvotes: 5

Related Questions