Skip to content
Advertisement

React text dropdown toggle (toggles all)

I am trying to make a small text dropdown. When you click on the heading text, the p tag will show. It is working, but.. it is toggling all of them, when I only click on of them. I have multiple “li” tags with text and the function. So I am not looping anything

JavaScript

Advertisement

Answer

Based on your question and the comments, you are reusing the isActive state across multiple elements in the same component, which means that each element does not have its own isActive state: they all share the same state globally.

You can create a child component that handles the state exclusively, while allowing it to receive contents in the form of props, e.g. for the heading and content:

JavaScript

Then, in your original parent component it’s just a matter of using <MyComponent> to handle all your <li> entries:

JavaScript

You can see a proof-of-concept example here:

Edit aged-field-nj1z6

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