How to implement an Accordion with React in less than 5 mins

How to implement an Accordion with React in less than 5 mins

There are two versions of accordion I know, one is too easy to implement because multiple cards could be open at a time, and the second version only one card is open at a time or no one open at all. I was looking for a tutorial to do it and found one, even though I liked how the implementation is super organized and reuseable, but could not wrap my head around all the variables and files. you can have a look at the demo to know what I mean.

After thirty minutes of thinking and trying, I came up with my own solution. Let me explain, what I did.

We need two Components: Card, Accordion. The Card has the following props: id, CurrentCard, setCurrentCard Accordion: useState hook

The Accordion component is just the Cards container with one hook. The card component has a button and a body. The button runs the function to tell the Accordion to open the card if it is closed, or to close it if it is open. The body will be displayed only if the id is equal to the currentCard otherwise it will be hidden.

Once the accordion component received the id through the setCurrentCard function from the card, the function task is to reassign the currentCard with the parameter (card id). now the id and currentCard are equivalent and the body should be displayed after Accordion rerendered.

Styling might be a bit of a distraction when trying to understand a functionality or how things work, so I created an additional component with some styles and content. I added two props to cardBody component to receive a content.

Thanks for reading