How to access correct 'this' inside map: ReactJS [duplicate]

For example I have a react component with two binding methods:

import React from 'react';

class Comments extends React.Component {
    constructor(props) {
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleRemoveComment = this.handleRemoveComment.bind(this);
    }

    handleSubmit(e) {
        .....
    }

    handleRemoveComment(e) {
        //this.props.removeComment(null, this.props.params, i);
    }

    renderComment(comment, i) {
        return(
            <div className="comment" key={i}>
                  .....
                  <button 
                       onClick={this.handleRemoveComment}
                       className="remove-comment">
                       &times;
                  </button>
            </div>
        )
    }

    render() {
        return(
            <div className="comments">

                {this.props.postComments.map(this.renderComment)}

                .....
            </div>
        )
    }
}

export default Comments;

In above code, I have two binding method: one is handleSubmit and one is handleRemoveComment. handleSubmit function worked but handleRemoveComment doesn't. When running, It returns error:

TypeError: Cannot read property 'handleRemoveComment' of undefined

Answers:

Answer

Issue is with this line:

{this.props.postComments.map( this.renderComment )}

Because you forgot to bind renderComment, map callback method, so this inside renderComment method will not refer to the class context.

Use any one of these solutions, it will work.

1- Use this line in constructor:

this.renderComment = this.renderComment.bind(this) ;

2- Pass this with with map like:

{this.props.postComments.map(this.renderComment, this)}

3- Use Arrow function with renderComment method, like this:

renderComment = (comment, i) => {
    .....

or use the map inside the renderComment function (i used to prefer this way), like this:

renderComment() {
    return this.props.postComments.map((comment, i) => {
        return(
            <div className="comment" key={i}>
                <p>
                    <strong>{comment.user}</strong>
                    {comment.text}
                    <button 
                        onClick={this.handleRemoveComment}
                        className="remove-comment">
                        &times;
                    </button>
                </p>
            </div>
        )
    })
}

And call this method from render, in this case binding of renderComment is not required:

{this.renderComment()}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.