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;