gospecomid12
gospecomid12

Reputation: 1012

Show only clicked element in array and hide the others React

I'm making an Q/A page and I got questions that is visible and when I click them I display the answer which is hidden froms start. So I got an array of objects which i .map() in the jsx and display. That's working well.

But when i click a question it displays all the answers instead of only displaying the answer for that specific question I click.

Here's my JSX:

  <div className="questions">
    {md.questionsArray.map((item, i) => (
      <div
        key={i}
        className="question"
        onClick={() => handleOpen(item.question)} // HERES THE QUESTION I CLICK
      >
        <p>{item.question}</p>
        {openQuestion ? <p>{item.answer}</p> : null} // HERES THE ANSWER THAT IS VISIBLE AFTER CLICK 
      </div>
    ))}
  </div>

Here's my function:

  const [openQuestion, setOpenQuestion] = useState(false)

  const handleOpen = x => {
    let clickedItem = md.questionsArray.find( // HERE I CAN FIND WHICH QUESTION I CLICK
      item => item.question === x
    )
    console.log('clicked item: ', clickedItem)

    if (openQuestion === false) { // HERE I OPEN AND CLOSE QUESTIONS
      setOpenQuestion(true)
    } else {
      setOpenQuestion(false)
    }
  }

Upvotes: 0

Views: 1162

Answers (1)

hellogoodnight
hellogoodnight

Reputation: 2139

Use a unique value from the question to identify what question is open.

const [openQuestion, setOpenQuestion] = useState(null)

{md.questionsArray.map((item, i) => (
      <div
        key={i}
        className="question"
        onClick={() => setOpenQuestion(item.question === openQuestion 
                                       ? null 
                                       : item.question)}>
        <p>{item.question}</p>
        {openQuestion === item.question && <p>{item.answer}</p>} 
      </div>
    ))}

Upvotes: 3

Related Questions