Home > OS >  React/JS, useState - Why will Button change text only twice when taking text out of Array with 10 el
React/JS, useState - Why will Button change text only twice when taking text out of Array with 10 el

Time:08-24

I want to have a Button that changes the text ten times.

  • So I made an array clickArraywith 10 strings, and a counter let count = 0.
  • Made a function setCount()with an if else that ticks up the counter and turns back to zero after 10.
const [buttonText, setButtonText] = useState("Click")

let count = 0

const setCount = () => {
    if (count < clickArr.length) {
      count   
    } else {
      count = 0 
    }
  }

 const handleClick = () => {
    setButtonText(clickArr[count])
    setCount()
  }



// in return():
<div className="button" onClick={handleClick}>{buttonText}</div>

--> No error is thrown, but the counter behaves weird. Console logging everything brings no clarity.

  • First click: Button changes text from default text "Click" to clickArr[0] as it should. setCount ticks count to 1
  • Second click: Nothing happens.
  • Third click: Counter ticks to 3
  • Fourth click: Counter ticks to 1

console.log(setCount()) is "undefined"

I think i dont store count correctly, but thats just a guess. Thanks in advance!

CodePudding user response:

If my crystal ball is correct, you want a component where a button's text is picked from an array on each click of the button.

If so, then you'll want to just derive the button text based on the array (which could be state if required) and the click number state atom.

  • The setCount invocation here is using the functional update form of setState, so it doesn't need to read the count state itself (and is safe from possible stale state closure problems).
  • I'm using the modulus operator % so the counting operation does not need to even know how many texts there are.
const clickArr = ["Click", "Clack", "Bleep", "Bloop"];

function Component() {
  const [count, setCount] = React.useState(0);
  const buttonText = clickArr[count % clickArr.length];
  const handleClick = () => setCount((c) => c   1);
  return (
    <div className="button" onClick={handleClick}>
      {buttonText}
    </div>
  );
}
  • Related