Traverse a . map() in inside . map() React jsx

Asked

Viewed 176 times

0

I’m using React with Typescript. Is it possible to go array inside an array? This is my array:

const menu: Array<{name: string; to: string; icon?: ReactNode; submenu?: any}> = [
            {
                name: 'Segmento', to: '/', icon: Label,
                submenu: [
                    { name: 'Segmento 1', to: '/Segmento_1', icon: Label }, { name: 'Segmento 2', to: '/', icon: Label },
                    { name: 'Segmento 1', to: '/Segmento_1', icon: Label }, { name: 'Segmento 2', to: '/', icon: Label },
                ],
            },
        ]

I’m doing it like this to go through...

export default function MenuTreeView() {

   const classes = useStyles();

    return (
        <TreeView
            className={classes.root}
            defaultExpanded={['']}
            defaultCollapseIcon={< ArrowDropDownIcon />}
            defaultExpandIcon={< ArrowRightIcon />}
            defaultEndIcon={< div style={{ width: 24 }} />}
        >
            {menu.map((item, index) => (
                <StyledTreeItem nodeId={index} labelText={item.name} labelIcon={item.icon} />
                item.submenu.map((subitem, subindex) => (
                    <StyledTreeItem
                        nodeId={subndex}
                        labelText={subitem.name}
                        labelIcon={subitem.icon}
                    /> 
                ))
                </StyledTreeItem >
            ))}
        </TreeView >
    );
 }

but the build error

inserir a descrição da imagem aqui

Thank you.

1 answer

1

You need to put the second map inside keys as well, since it will be inside a JSX element.

Edit Note that the Styledtreeitem element is being closed twice, remove the self closing tag from that element.

export default function MenuTreeView() {

   const classes = useStyles();

    return (
        <TreeView
            className={classes.root}
            defaultExpanded={['']}
            defaultCollapseIcon={<ArrowDropDownIcon />}
            defaultExpandIcon={<ArrowRightIcon />}
            defaultEndIcon={<div style={{ width: 24 }} />}
        >
            {
                menu.map((item, index) => (
                    <StyledTreeItem nodeId={index} labelText={item.name} labelIcon={item.icon}>
                        {
                            item.submenu.map((subitem, subindex) => (
                                <StyledTreeItem
                                    nodeId={subndex}
                                    labelText={subitem.name}
                                    labelIcon={subitem.icon}
                                /> 
                            ))
                        }
                    </StyledTreeItem>
                ))
            }
        </TreeView>
    );
 }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.