struensee
struensee

Reputation: 606

Adding a 'count clicks' function to a boolean button in React

I've built a simple message board with a star button next to each comment. I've got the button working (toggles on/off as a bool). I'm trying to add a counter that responds to the button (count goes down if star is unclicked and vice-versa). I want to pass this value to an element in the header that states "Number of favorites: n". The point is to tell the user how many comments they have favorited. The tricky part (for me anyway) is counting all of the stars' true/false status.

I've tried building a counter, but I just can't figure out how to put the pieces together.

This is the button:

function Favorite() {
  const [state, setState] = useState(true);

  function toggle() {
    state ? setState(false) : setState(true);
  }

  return (
    <div className="Favorite" onClick={toggle} id="clicks">
      {state ? <span>☆</span> : <span>🌟 </span>}
    </div>
  );
}

Even with the counter, I don't know what I would pass into the div element in my header that lists the count next to "Number of Favorites: n". I'm sure it'd be some element wrapped in {}, just not sure what.

Upvotes: 0

Views: 1981

Answers (1)

Vonder
Vonder

Reputation: 4061

You need to declare the counter:

 const [counter, setCounter] = useState(0);

and then increment it each time the state is set to true

setCounter(counter + 1)

and decrement when false. Then display the counter with {counter}

Here is the code:

function Favorite() {

const [state, setState] = useState(true);
const [counter, setCounter] = useState(0);

function toggle() {

setState(!state);
if (state === true) {
  setCounter(counter +1);

} else {
  setCounter(counter -1);

}
}
return (
<div className="Favorite" onClick={toggle} id="clicks">Counter: 
{counter} 
  {state ? <span>☆</span> : <span>🌟 </span>}
 </div>
);
}

Upvotes: 2

Related Questions