I am trying to create a Collapse menu from array data,
Currently, when I click on any menu all sub menus expand
I believe my issue lies in not being able to set a unique "open" state for each Main menu
I want to avoid assigning a "state" to accommodate potential future data that may have 3 or 4 levels
I am using React.js and material-ui
Please assist me with this problem
Thank you in advance
const myData = [
{
id: '1',
nameHeader: 'Header1',
subMenu: [{ id: '1', name: 'subMenu1' }, { id: '2', name: 'subMenu2' }]
},
{
id: '2',
nameHeader: 'Header2',
subMenu: [{ id: '1', name: 'subMenu1' }, { id: '2', name: 'subMenu2' }]
}
]
class Myclass extends Component {
state = { open: false }
handleClick = () => {
this.setState(state => ({ open: !state.open }))
}
render() {
const { open } = this.state
return (
<div style={{ marginRight: '15px' }}>
<List component="nav">
{myData.map(each => (
<React.Fragment key={each.id}>
<ListItem button onClick={this.handleClick}>
<ListItemText inset primary={each.nameHeader} />
{open ? <ExpandLess /> : <ExpandMore />}
</ListItem>
<Divider />
<Collapse in={open} timeout="auto" unmountOnExit>
<List component="div" disablePadding>
{each.subMenu.map(subData => (
<ListItem key={subData.id} button>
<ListItemText inset primary={subData.name} />
</ListItem>
))}
</List>
</Collapse>
</React.Fragment>
))}
</List>
</div>
)
}
}
export default Myclass