React.js – Can’t read property of undefined

The actual problem here is that the this context is not defined in your handleChangeOnMonth function. This is caused because of the way that javascript handles the contexts of functions, basically when calling functions if you are not calling them directly from the object, and they are not bound they will not have a defined context, and since you are passing the function as a parameter to the input component, it loses the context.

The simplest way to fix this is to bind the function, I suggest that you bind the function in the constructor, like so:

class MonthsTable extends Component {
  constructor(props, context){
    super(props, context);
    this.handleChangeOnMonth = this.handleChangeOnMonth.bind(this);
  }
  handleChangeOnMonth(e){ 
    this.props.setMonth(e.target.id, e.target.value);
  }
  render(){
    return (<form>
      {this.props.months.map((e, i) =>
         <input
          type='number'
          id={i} 
          key={i} 
          value={this.props.months[i]}
          onChange={this.handleChangeOnMonth} />)}
    </form>)
  }
}

alternatively if you are using decorators you could use the core-decorators package to do this in a more elegant way:

import {autobind} from "core-decorators"

@autobind
class MonthsTable extends Component {     
  handleChangeOnMonth(e){ 
    this.props.setMonth(e.target.id, e.target.value);
  }
  render(){
    return (<form>
      {this.props.months.map((e, i) =>
         <input
          type='number'
          id={i} 
          key={i} 
          value={this.props.months[i]}
          onChange={this.handleChangeOnMonth} />)}
    </form>)
  }
}

Leave a Comment