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>
);
}
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With