Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
169
rated 0 times [  175] [ 6]  / answers: 1 / hits: 16832  / 7 Years ago, wed, april 19, 2017, 12:00:00

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)

More From » reactjs

 Answers
7

Solution for issue you mentioned in edit part.



Reason is, you are loosing the context in map callback function, you need to bind this (class context) with callback function or Use arrow function, it will solve your issue.



By using arrow function:



renderBooks(){
return this.props.myBooks.data.map((book) => { //here
return (
.....
);
});
}


Or use .bind(this) with callback function, like this:



renderBooks(){
return this.props.myBooks.data.map(function (book) {
return (
.....
);
}.bind(this)); //here
}

[#58099] Monday, April 17, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
travion

Total Points: 137
Total Questions: 96
Total Answers: 103

Location: India
Member since Wed, Aug 4, 2021
3 Years ago
travion questions
Mon, Dec 16, 19, 00:00, 5 Years ago
Sat, Oct 19, 19, 00:00, 5 Years ago
Fri, Sep 20, 19, 00:00, 5 Years ago
Wed, Nov 14, 18, 00:00, 6 Years ago
Sun, Oct 28, 18, 00:00, 6 Years ago
;