undefined
undefined

Reputation: 441

How to display a div element on a specific key in a map in react

I have a list which has a buton next to it:

list 1 (button)

list 2 (button)

list 3 (button)

Inside a map:

 const [ show, setShow ] = useState(true);

 const showOptions = () => {
   setShow(!show);
 }

return (
  {list.map((a, i) = (
    <div key = {i} >
      {a.listAll}

      <button onClick={showOptions}>Show</button>

      {!show ?
      <div>{a.listOfOptions}</div> : null   
      }
    </div>
  ))}
 )

On button click the div element shows below, but it shows below all the list. How do I make it show only on a specific list? for example when I click list 3 it will display only below list 3.

Upvotes: 1

Views: 1075

Answers (1)

Axnyff
Axnyff

Reputation: 9964

You should change the state to reflect the index for which you want the show the list:

 const [ listIndex, setListIndex ] = useState(undefined);

return (
  {list.map((a, i) = (
    <div key = {i} >
      {a.listAll}

      <button onClick={() => listIndex === i ? setListIndex(undefined) : setListIndex(i)}>Show</button>

      {i === listIndex ?
      <div>{a.listOfOptions}</div> : null   
      }
    </div>
  ))}
 )

Upvotes: 1

Related Questions