0

I am trying to make a small function, which makes a likable Button. My function should work, but the error I get is too many re-renders (even tough the setState only gets called onClick) Code below:

    function ClickMeToLike(){
  const [isLiked, setIsLiked] = useState(false);

  return (
    <Col><p>
    {
    isLiked ?
    <Icon.Heart onClick={setIsLiked(true)}/> :
    <Icon.HeartFill onClick={setIsLiked(false)}/>
    }
    </p></Col>
  )
}

2 Answers2

1

you need to use an arrow function in your onClick

try this

onClick = {() => setIsLiked(true)}

best practice is to use what the answer above me is though and define a separate function to handle your clicks

wjpayne83
  • 192
  • 1
  • 11
0

Yes, you shouldn't handle clicking inside a return. You need to define a separate function for handling the click.

function ClickMeToLike(){
  const [isLiked, setIsLiked] = React.useState(false);

  onClick = () => setIsLiked(!isLiked);
  
  return (
    <div>
      <button onClick={onClick}>Button</button>
      {isLiked?"clicked":"not clicked"}
    </div>
  )
}
jaesle
  • 548
  • 4
  • 14