1

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])} // 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

How can I do this?

1

1 Answer 1

1

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" />
        </>
Sign up to request clarification or add additional context in comments.

1 Comment

thanks @Sonia Aguilar this helped. Is working now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.