Paulos3000 Paulos3000 - 2 months ago 15
Javascript Question

Unable to call onClick function in React

I have a stateless functional component called

Likes
. Within it, I have two functions:
handleLikePlus()
and
handleLikeMinus()
. I want to trigger each one of them respectively when clicking on the up, or down arrows within the
Likes
component.

Here is the code for my component

function Likes( {likes} ) {
function handleLikePlus() {
this.setState({
likes: this.state.likes + 1
});
};
function handleLikeMinus() {
this.setState({
likes: this.state.likes - 1
});
};
return (
<div>
<div onClick={this.handleLikePlus()}>
<h5><i className="fa fa-arrow-up" aria-hidden="true"></i></h5>
</div>
<div>
<h4>{likes}</h4>
</div>
<div onClick={this.handleLikeMinus()}>
<h5><i className="fa fa-arrow-down" aria-hidden="true"></i></h5>
</div>
</div>
);
}


My console returns:

Uncaught TypeError: cannot read property 'handleLikePlus' of undefined


Where am I going wrong? Is it a simple syntax error? Or am I calling the function in the wrong way?

Thanks in advance.

Answer

You're using a stateless component, but you're still trying to use setState() — that won't work. If you need state, use a normal component.

Also, as the error reads, handleLikePlus cannot be accessed from this, since there is no this inside your function.