Skip to content
Advertisement

Only allow one React Accordion to be expanded at once

I have an array of data that will be used to create accordions, I’d like to make it so that only one of them can be expanded at once (i.e, if the user expands accordion #1 and then #2, #1 will un-expand)

I have this code:

JavaScript

I’m quite new to React so I suspect I’ve made a mistake with the states. Any help / tips would be appreciated! Thank you

Advertisement

Answer

It looks like you tried putting state and handlers in both the parent MyAccordions and the children MyAccordion components. If you want only one accordion open at-a-time then I suggest placing the state in the parent component so it can manage what is open/expanded. Use the children accordion ids as the basis of determining which should expand.

Parent

JavaScript

Child

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement