0

I'm trying to call the deletePost(index) method that is in the ShowPost class from a button that is dynamically rendered in the render() step in React. The button that says "click me" is able to be called, and will print the first (aka [0] position) of my array this.state.posts, while the button(s) that says "Delete" that have been dynamically created break the code. It gives me TypeError: Cannot read property 'deletePost' of undefined. I'm thinking that I need to somehow "pass" the method deletePost into my "inner" components (aka the buttons) that are dynamically being rendered?

class ShowPost extends Component {

  constructor(props) {
      super(props);
      this.state = {
        posts: []
      };
      this.setState = this.setState.bind(this);
      this.deletePost = this.deletePost.bind(this);
    }

  deletePost(index){
    console.log(this.state.posts[index]);
  }

  render(){
    return (
      <React.Fragment>
        <button onClick={this.deletePost.bind(this, 0)} > click me </button>
          <div className="list-group">
          {
            this.state.posts.reverse().map(function(post,index) {
              return <div key={index} className="list-group-item active">
              <h4 className="list-group-item-heading">{post.Title}</h4>
              <p className="list-group-item-text">{post.Subject}</p>
              <button onClick={this.deletePost.bind(this, 0)} > Delete </button>
              </div>
            })
          }
          </div>
      </React.Fragment>
    )
  }
}

export default ShowPost;
shaotime
  • 39
  • 1
  • 3
  • 1
    use `arrow` function instead of normal function for your `map` like `this.state.posts.reverse().map((post,index) => {` – Panther Nov 28 '18 at 09:02
  • thanks! that did the trick. when would be using function() instead of arrows better? it seems so far that the arrow function is better overall – shaotime Nov 28 '18 at 09:04

1 Answers1

0

Since the render button a function, you can't get this. Change to arrow function.

this.state.posts.reverse().map(post => (
          return <div key={post.Id} className="list-group-item active">
          <h4 className="list-group-item-heading">{post.Title}</h4>
          <p className="list-group-item-text">{post.Subject}</p>
          <button onClick={this.deletePost.bind(this, 0)} > Delete </button>
          </div>
        ))

Other thing is you should use post.id as key rather than index.

Daniel Tran
  • 6,083
  • 12
  • 25