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 ?

1

2 Answers

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) } __^^^^___ 

In addition to @Alexander answer, you can bind eachNote to this in constructor too and it should work:

this.eachNote = this.eachNote.bind(this); 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy