I'm trying to recursively render AntDesign Menu. I found some examples how to do it based on just normal ul
and li
tags and they works, but when I'm trying changing li
to Menu.Item
and ul
to SubMenu
then every item is active and with wrong styles.
example data:
[
{fileName: "test1"}
{fileName: "test2"}
{fileName: "x",
items: [
{fileName: 'test3'}
]}
]
My attemp:
<Menu
mode="inline"
onClick={(e) => handleClick(e)}
>
{data.map((item) => (
<ListItem item={item} />
))}
</Menu>
const ListItem = ({ item }: iLProps) => {
let children = null;
if (item.items && item.items.length) {
children = (
<SubMenu key={item.fileName} title={item.fileName}>
{item.items.map((nestedItem: NavItem) => (
<ListItem item={nestedItem} />
))}
</SubMenu>
);
}
return (
<Menu.Item key={item.fileName}>
{item.fileName}
{children}
</Menu.Item>
);
};
If someone need working examples on codesandbox then I can add.
CodePudding user response:
This code works for me:
const recursiveMenu = (data) => {
return data.map(({ fileName, items = [] }) => {
console.log({ fileName, items });
if (!items?.length) {
return <Item key={Math.random()}>{fileName}</Item>;
}
return (
<SubMenu key={Math.random()} title={fileName}>
{recursiveMenu(items)}
</SubMenu>
);
});
};
And in the Menu component:
export default function App() {
return <Menu mode="inline">{recursiveMenu(data)}</Menu>;
}
Here is a working codesandbox link: https://codesandbox.io/s/sleepy-wind-55otl