0

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.

2
  • 2
    the whole point of stateless means no this. and certainly no thie.state and especially no this.setState. Stateless right? pass those functions down from a parent. also it should be onClick={handleLikePlus} not onClick={handlLikePlus()}. you're passing a function reference, not the result of calling a function Commented Sep 21, 2016 at 18:40
  • Oh man, that was stupid... <facepalm>. Clue's in the name, right? :) So, solution is pass it from a parent. Also very useful to know that it is a function reference as opposed to a function call. Thanks! Commented Sep 21, 2016 at 18:47

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.