Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS ES6 function binding - Uncaught TypeError: Cannot read property 'update' of undefined

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 ?

like image 554
cucucool Avatar asked Oct 29 '25 11:10

cucucool


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) }
                                    __^^^^___
like image 141
Oleksandr T. Avatar answered Oct 31 '25 23:10

Oleksandr T.


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

this.eachNote = this.eachNote.bind(this);
like image 36
madox2 Avatar answered Nov 01 '25 00:11

madox2