I have seen other people ask similar questions to this and I have tried implementing the answers they received. But I am still getting a console error. I mean the code is working as expected I just hate having console errors.
Here is my code
const Accordion = () => {
const [clicked, setClicked] = useState(false);
const toggle = index => {
if (clicked === index) {
//if clicked question is already active, then close it
return setClicked(null);
}
setClicked(index);
};
return (
<IconContext.Provider value={{ color: '#441d0c', size: '25px' }}>
<AccordionContainer>
<FaqContainer>
{FaqData.map((item, index) => {
return (
<>
<QuestionWrapper onClick={() => toggle(index)} key={index}>
<h2>{item.question}</h2>
<span>{clicked === index ? <FiMinus /> : <FiPlus />}</span>
</QuestionWrapper>
{clicked === index ? (
<AnswerDropdown>
<p>{item.answer}</p>
</AnswerDropdown>
) : null}
</>
)
})}
</FaqContainer>
</AccordionContainer>
</IconContext.Provider>
)
}
and the console error I get:
Warning: Each child in a list should have a unique "key" prop.
To me it looks like each child DOES have a unique key, What am I missing?
The key should be set at the root object of your map. In order to fix the warning, you can replace the react fragment (<>) by a div and set the key like this:
{FaqData.map((item, index) => {
return (
<div key={index}>
<QuestionWrapper onClick={() => toggle(index)}>
<h2>{item.question}</h2>
<span>{clicked === index ? <FiMinus /> : <FiPlus />}</span>
</QuestionWrapper>
{clicked === index ? (
<AnswerDropdown>
<p>{item.answer}</p>
</AnswerDropdown>
) : null}
</div>
)
})}