I know the title seems very basic and easy but pls help me, so basically when i try to open one menu, it opens all menus
import React from "react";
export default function App() {
const [active, setActive] = React.useState(false);
function handleClick() {
setActive(!active);
}
const text = [
{
id: 1,
name: "Hello",
subText: [
{
id: 1,
name: "Sub Hello"
}
]
},
{
id: 2,
name: "Bye",
subText: [
{
id: 2,
name: "Sub Bye"
}
]
}
];
return (
<div style={{ backgroundColor: "gray", padding: 4 }}>
{text?.map(({ name, id, subText }) => (
<div style={{ display: "flex", alignItems: "center" }}>
<ul style={{ width: 100 }}>
<li style={{ cursor: "pointer" }} onClick={handleClick}>
{name}
</li>
</ul>
<div>
{active &&
subText?.map(({ name, id }) => (
<ul key={id}>
<li>{name}</li>
</ul>
))}
</div>
</div>
))}
</div>
);
}
here is the live code:
https://codesandbox.io/s/angry-moser-dh4mit?file=/src/App.js:0-1051
>Solution :
Passing the parent menu id for checking which submenu should be opened would help.
Attaching the changed code below.
Just passed id and hold it in the state when clicked. otherwise the state would be undefined.
export default function App() {
const [active, setActive] = React.useState(undefined);
function handleClick(id) {
setActive(id === active ? undefined :id);
}
const text = [
{
id: 1,
name: "Hello",
subText: [
{
id: 1,
name: "Sub Hello"
}
]
},
{
id: 2,
name: "Bye",
subText: [
{
id: 2,
name: "Sub Bye"
}
]
}
];
return (
<div style={{ backgroundColor: "gray", padding: 4 }}>
{text?.map(({ name, id, subText }) => (
<div style={{ display: "flex", alignItems: "center" }}>
<ul style={{ width: 100 }}>
<li style={{ cursor: "pointer" }} onClick={() => handleClick(id)}>
{name}
</li>
</ul>
<div>
{active === id &&
subText?.map(({ name, id }) => (
<ul key={id}>
<li>{name}</li>
</ul>
))}
</div>
</div>
))}
</div>
);
}