I'll go straight to the point. This is the component I have in a ReactJS application:
class BooksList extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
e.preventDefault();
console.log(The link was clicked);
}
render() {
return (
<div>
<a className=btn btn-success onClick={handleClick}>
Add to cart
</a>
</div>
);
}
}
Why do I get the following error when the component is loaded?
Uncaught ReferenceError: handleClick is not defined
EDIT:
After you answers I changed my code to this:
handleClick(e) {
e.preventDefault();
console.log(Item added to the cart);
}
renderBooks(){
return this.props.myBooks.data.map(function(book){
return (
<div className=row>
<table className=table-responsive>
<tbody>
<tr>
<td>
<p className=bookTitle>{book.title}</p>
</td>
</tr>
<tr>
<td>
<button value={book._id} onClick={this.handleClick}>Add to cart</button>
</td>
</tr>
</tbody>
</table>
</div>
);
});
}
}
render() {
return (
<div>
<div>
<h3>Buy our books</h3>
{this.renderBooks()}
</div>
</div>
);
}
As you can see I have .map
which iterate through a list of books.
For each of the books I have a button that, if clicked, will add the specific book to the user's cart.
If I follow @Tharaka Wijebandara answer I can make a button work outside .map
but in this case I still get the error:
Uncaught (in promise) TypeError: Cannot read property 'handleClick' of undefined
at http://localhost:8080/bundle.js:41331:89
at Array.map (native)