Robert
Robert

Reputation: 333

Toggle through Reactjs Mapped Array

I'm trying to figure out how to only show one item in my array at a time and then click back and fourth through them using to buttons. Currently right now if there are 4 items in the array all 4 are shown on the page. But I'd like to show them one at a time and then be back to click back and fourth through them. I've built this using hooks.

Here is my current code:

<div>
 {[...Array(stepBlock)].map((e, i) => 
   <div className={'stepBlock'} key={i}>
        <div>{details[i].name}</div>
   </div>
 )}
 </div>
 <div>
    <div>previous</div>
    <div>next</div> 
  </div>

Any help would be greatly appreciated.

Upvotes: 0

Views: 46

Answers (1)

Arun Kumar Mohan
Arun Kumar Mohan

Reputation: 11915

You can create an index state variable to track the active index state. Since you want to render all the array items but hide the inactive ones, you can conditionally add a hidden CSS class based on the active index. The 'Previous' and 'Next' buttons can update the state by calling setIndex (the state updater function). You should pass a function to setIndex since the new state depends on the previous state. And you can disable the buttons if the index is out of bounds.

const [index, setIndex] = useState(0)
const names = ['John', 'Paul', 'George', 'Ringo']
<>
  {names.map((name, i) => (
    <div key={i} className={`name ${i !== index ? 'hidden' : ''}`}>
      {name}
    </div>
  ))}
  <div>
    <button
      disabled={index === 0}
      onClick={() => setIndex((prevIndex) => prevIndex - 1)}
      className="button"
    >
      Previous
    </button>{' '}
    <button
      disabled={index === names.length - 1}
      onClick={() => setIndex((prevIndex) => prevIndex + 1)}
      className="button next-button"
    >
      Next
    </button>
  </div>
</>

Edit romantic-jackson-q7fkh

Upvotes: 2

Related Questions