Reputation: 772
I've been searching the web for answers to my question, but without success. I am trying to add a simple react click handler to my button, but I can't seem to make it work. It is probably something really simple, I just can't wrap my head around it.
Here is my code:
export default class ReviewBox extends Component {
deleteReview() {
console.log("hey");
}
render() {
const {reviews, date, lectureId} = this.props;
const that = this;
return (
<div className="container content-sm">
<div className="headline"><h2>Reviews</h2> <span>{date}</span></div>
<div className="row margin-bottom-20">
{reviews.map(review => {
return(
<div className="col-md-3 col-sm-6">
<div className="thumbnails thumbnail-style thumbnail-kenburn">
<div className="caption">
<h3>{review.comment}</h3> <br />
<button className="btn btn-danger" onClick={this.deleteReview()}>Delete</button>
</div>
</div>
</div>
)
})}
</div>
<hr />
<AddReview lectureId={lectureId} />
</div>
)
}
}
It refuses to fire the function when I click a button. I've tried with .bind(this) and onClick={() => this.deleteReview} etc.
All help appreciated!
Upvotes: 3
Views: 5391
Reputation: 772
Ah, now I understand. It is because I am rendering the react on serverside, that's why the click handler doesn't work.
I will have to render the JS on the client, in order for it to work :)
Upvotes: 0
Reputation: 851
Removing ()
from the onClick
function call and using { this.deleteReview }
will indeed fire up the method, but if you need to bind this
as well inside that method, go with @duwalanise
answer.
Upvotes: 0
Reputation: 1302
I think you are missing braces () in arrow function
<button className="btn btn-danger" onClick={() => this.deleteReview()}>Delete</button>
Upvotes: 7
Reputation: 465
i think this will help you.....
export default class ReviewBox extends Component {
deleteReview() {
console.log("hey");
},
render() {
const {reviews, date, lectureId} = this.props;
const that = this;
return (
<div className="container content-sm">
<div className="headline"><h2>Reviews</h2> <span>{date}</span></div>
<div className="row margin-bottom-20">
{reviews.map(review => {
return(
<div className="col-md-3 col-sm-6">
<div className="thumbnails thumbnail-style thumbnail-kenburn">
<div className="caption">
<h3>{review.comment}</h3> <br />
<button className="btn btn-danger" onClick={this.deleteReview}>Delete</button>
</div>
</div>
</div>
)
})}
</div>
<hr />
<AddReview lectureId={lectureId} />
</div>
)
}
}
Upvotes: 1