Ad

ReactJS ES6 Function Binding - Uncaught TypeError: Cannot Read Property 'update' Of Undefined

- 1 answer

I am working on ReactJS with multiple components in parent-child mode. In the following example, update function is passed on to the Note component (child) from Board component (parent). When I execute the code, I get Uncaught TypeError: Cannot read property 'update' of undefined error and I have a bind(this) in the constructor.

import React, { Component } from 'react';
import Note from './note';

export default class Board extends Component {

  constructor(props) {
    super(props);
    this.state = {
       notes: [
        'Call Bill',
        'Email list',
        'Fix evernote tags'
       ]
    };
    this.update = this.update.bind(this);
  }

 update(newText,i){
    alert('update triggered');
    var arr = this.state.notes;
    arr[i]=newText;
    this.setState({notes:arr});
  };

  eachNote(note,i){
    return(
      <Note key={i} index={i} onNoteChange={this.update}>{note}</Note>
    );
  };

  render() {
    return (
      <div className="board">
        { this.state.notes.map(this.eachNote) }
      </div>
    );
  }
}

I would appreciate any help in resolving this issue. And once the binding in place, I should be able to call this parent method in the child component right ?

Ad

Answer

this in eachNote does not refer to Board, it refers to global scope(in browser it is window) or if you use strict mode(I think you use it) it will be undefined, you need set it

{ this.state.notes.map(this.eachNote, this) }
                                    __^^^^___
Ad
source: stackoverflow.com
Ad