Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React/JS, useState – Why will Button change text only twice when taking text out of Array with 10 elements?

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading