For a preact tree component I want to achieve that the lists of child elements are shown only when the user clicks the corresponding button of the parent element. With my code so far I can just show or hide ALL child lists of the next layers when clicking the button of one parent list.
This is my list of tree elements:
let list = [
{
"name": "rootListItem1",
"id": "1"
},
{
"name": "rootListItem2",
"id": "2",
"list": [
{
"name": "secondLayerItem1",
"id": "21",
"list": [
{
"name": "thirdLayerItem11",
"id": "211"
},
{
"name": "thirdLayerItem12",
"id": "212",
"list": [
{
"name": "fourthLayerItem121",
"id": "2121",
"list": [
{
"name": "fifthLayerItem1211",
"id": "21211"
},
{
"name": "fifthLayerItem1212",
"id": "21212"
},
]
},
{
"name": "fourthLayerItem122",
"id": "2122"
},
]
},
]
},
{
"name": "secondLayerItem2",
"id": "22",
"list": [
{
"name": "thirdLayerItem21",
"id": "221"
},
{
"name": "thirdLayerItem22",
"id": "222"
}
]
}
]
},
{
"name": "rootListItem3",
"id": "3"
},
{
"name": "rootListItem4",
"id": "4"
}
];
And this is my Tree component:
const Tree = function (props) {
const [visible, setVisibility] = useState(false);
return (
<ul>
{
props.list.map(listItem =>
<>
<div class="row">
<span class={"caret" + (visible ? " caret-down" : "")}></span>
<input type="checkbox" name={listItem.name} id={listItem.id} value={listItem.id}/>
<button id={listItem.id} class="dropdown-list" onclick={() => {setVisibility(!visible)}}>{listItem.name}</button>
</div>
<li id="dropdown-content" class={"dropdown-content" + (visible ? " visible" : "")}>
{ listItem.list && <Tree list={listItem.list}/> }
</li>
</>)
}
</ul>
);
}
I tried to check if the id of the list items equals the target id of the button like this:
<button id={listItem.id} class="dropdown-list" onclick={(e) => {e.target.id === listItem.id ? setVisibility(!visible) : null}}>{listItem.name}</button>
But, for example, when I click the button of any of the secondLayerItems every thirdlayerItem becomes visible whether it belongs to the secondLayerItem or not. This is my first project with preact and I'm still new to programming at all. Does anybody know what I'm missing here and how I can achieve that when secondlayerItem2 is clicked only thirdLayerItem21 and thirdlayerItem22 are shown? I think something fundamental is missing here but I have no idea what the mistake is.
question from:
https://stackoverflow.com/questions/65904019/how-to-show-hide-content-of-nested-dropdown-lists-based-on-id