0

Hi i am trying to experiment with several code snippets in React. The following code generates a "Cannot read property 'removeComment' of undefined" type error. I have tried to different techniques to bind the function to the class as described in the react documentation https://reactjs.org/docs/faq-functions.html, but the problem persists. The following is my code:

class Board extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            comments: ["item1", "item2", "item3"]
        }
        this.removeComment = this.removeComment.bind(this);
        this.updateComment = this.updateComment.bind(this);
    }

    removeComment = (i) => {
        console.log("Removing comment " + i)
        var arr = this.state.comments;
        arr.splice(i, 1)
        this.setState({ Comments: arr })
    }

    updateComment = (newText, i) => {
        var arr = this.state.comments;
        arr[i] = newText
        this.setState({ comments: arr })

    }

    eachComment(text, i) {
        return (<Comment key={i} index={i}
            deleteComment={this.removeComment.bind(this)}
            updateCommentText={this.updateComment.bind(this)}>{text}</Comment>)
    }

    render() {
        return (
            <div>
                {
                    this.state.comments.map(this.eachComment)
                }
            </div>
        )
    }
}
Baboo
  • 4,008
  • 3
  • 18
  • 33
enu
  • 2,375
  • 2
  • 11
  • 12
  • There's no need to bind arrow functions. – Toby Dec 03 '18 at 21:30
  • `this` inside `eachComment` needs to the refer to the component as well: `this.state.comments.map(this.eachComment, this)`. There is no need to do `this.removeComment.bind(this)` or `this.updateComment.bind(this)` anywhere because you already defined them as class properties + arrow function: ` removeComment = (i) => {}`. If you don't know what this actually does then please read about it. – Felix Kling Dec 03 '18 at 21:37

0 Answers0