Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Hi everyone Im a bit stuck on a little problem. I'm trying to use react hooks to update the state of an array

Basically I have a list

const hatList = ['??', '??', '??', '??', '?', '??' ]

I want to loop through that list every time I do an onClick

<Button
  className="btn"
  btnText="Show Me Missing Koroks!"
  onClick={() => setHat(hatList[0 + 1])} // [ASK]: I know this gives me just the 2nd obj of the list, but how to loop through that list on every onClick ?
/>

This is the whole component:

const IndexPage = () => {

  const [hat, setHat] = React.useState([])
  
  const hatList = ['??', '??', '??', '??', '?', '??' ]

  return (
    <main>
      <header>
        <h1>For the Love of BOTW</h1>
        <h2>You thought you have found all the Koroks ?</h2>
      </header>
      <section>
        <Button
          className="btn"
          btnText="Show Me Missing Koroks!"
          onClick={() => setHat(hatList[0 + 1])}
        />
        <>
          <span role="img" aria-label='hat emoji various'>{hat}</span>
          <Icon name="korok" />
          <Icon name="mount" />
        </>
      </section>
    </main>
  )
}

export default IndexPage

Thanks in advance


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
500 views
Welcome To Ask or Share your Answers For Others

1 Answer

You have to use a state for the currentIndex.

const [currentIndex, setCurrentIndex] = useState(0)

// in onClickButton, increase this index
<Button
          className="btn"
          btnText="Show Me Missing Koroks!"
          onClick={() => setCurrentIndex((index) => index < hatList.length-1 ?  index+1 : 0)}
        />
        <>

To show current hat:

<>
          <span role="img" aria-label='hat emoji various'>{hatList[currentIndex] }</span>
          <Icon name="korok" />
          <Icon name="mount" />
        </>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...