Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to access `this.state` inside event handler function: ReactJS

Tags:

reactjs

How to get get React component state in that component function. This don't have objects associated to state. I am getting this.state undefined in Board removeComment function. Basically in Board removeComment function I want to remove comments element on that index(passed as argument).

class Board extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            comments:[
            "One",
            "Two",
            "Three",
            "four",
            "five"
        ]};
    };
    removeComment(index) {
        console.log('i was called',this.state);
    }
    render() {
        console.log(this.state);
        return (
            <div className="board">
                {
                    this.state.comments.map((text,i) => {
                        return (
                            <Comment  key ={i} index = {i} commentText={text} removeComment={this.removeComment}/>
                        )
                    })
                }
            </div>
        );
    }
}

class Comment extends React.Component {
  removeComment() {
    var index = this.props.index;
    this.props.removeComment(index);
  }
  render() {
    return(
      <div onClick={this.removeComment.bind(this)}>{this.props.commentText}</div>
    );
  }
}
like image 340
No one Avatar asked Apr 06 '17 09:04

No one


1 Answers

Because you forgot to bind the method removeComment in Board component, use this line:

removeComment={this.removeComment.bind(this)}

Use this in Board component:

<div className="board">
    {
        this.state.comments.map((text,i) => {
            return (
                <Comment  key ={i} index = {i} commentText={text} removeComment={this.removeComment.bind(this)}/>
            )
        })
    }
</div>
like image 65
Mayank Shukla Avatar answered Nov 13 '22 20:11

Mayank Shukla