Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React TypeScript callback reading undefined when using setState, but it will log the value

I am writing a react application, and for some reason I can not wrap my head around this issue. Below is a snippet, the only thing that should be needed:

onFirstNameChange(event: any){
    console.log(event.target.value)
    // this.setState({
    //     firstname: event.target.value
    // })
}

The commented out code will not run, it says it can not read properties of undefined. However when I log the events value it does it perfectly. Any ideas on why this is happening? It is an onchange event. It is also deeply nested, however the value does make it back.

like image 690
Chase Quinn Avatar asked Sep 04 '26 09:09

Chase Quinn


1 Answers

React components written in an ES6 class, do not autobind this to the component's methods. There are 2 solutions primarily. You may use choose either:

Either explicitly bind this in constructor

constructor(props) {
  super(props);

  // rest of code //

  this.state = {
    firstname: '',
  };

  // rest of code //

  this.onFirstNameChange = this.onFirstNameChange.bind(this);
}

Or use ES6 Arrow Function

onFirstNameChange = (event: any) => {
  console.log(event.target.value);

  this.setState({
    firstname: event.target.value
  });
}
like image 174
Vinay Sharma Avatar answered Sep 06 '26 23:09

Vinay Sharma