I've been trying to do a sort of toggle whereby you are able to click on a question to expand the answer. I've tried adapting the code from https://codesandbox.io/s/polished-rain-xnez0?file=/src/App.js, which was from another question on here.
Instead of creating a map in the parent component and passing in them separately to a reusable 'Expandable' component to render separate functional components as shown in the example, I tried creating the map within the FAQ component:
FAQ Expandable Component:
const FAQ = ({ questions }) => {
const [expanded, setExpanded] = useState(false);
const handleClick = () => {
setExpanded((prevExpanded) => !prevExpanded);
};
const renderedQuestions = questions.map((question, index) => {
return (
<React.Fragment key={question.id}>
<FAQIndividualWrapper>
<FAQTitle
className='title'
onClick={() => handleClick()}
>
{/* <i></i> */}
{question.title}
</FAQTitle>
<FAQContent className='content' style={{ display: expanded ? "block" : "none" }}>
{question.content}
</FAQContent>
</FAQIndividualWrapper>
</React.Fragment>
)
})
return (
<>
{renderedQuestions}
</>
)
Parent Component:
const questions = [
{
id: 1,
title: 'Question 1',
content: 'Answer 1'
},
{
id: 2,
title: 'Question 2',
content: 'Answer 2'
}
]
const FAQSection = () => {
return (
<FAQPageContainer>
<FAQWrapper>
<FAQ questions={questions} />
</FAQWrapper>
</FAQPageContainer>
)
}
However, my code results in all the answers being expanded on any click of either question. Why is this happening?
Also, how should I structure and fix the code for 'ideal' programming?
Thank you!