I am making a nested menu and submenus and everything has been done as of now.. I am now in the need to make this collapsible menu to get opened by default based on the id given..
You could also take a look at the complete working code snippet below,
const loadMenu = () => Promise.resolve([{id:"1",name:"One",children:[{id:"1.1",name:"One - one",children:[{id:"1.1.1",name:"One - one - one"},{id:"1.1.2",name:"One - one - two"},{id:"1.1.3",name:"One - one - three"}]}]},{id:"2",name:"Two",children:[{id:"2.1",name:"Two - one"}]},{id:"3",name:"Three",children:[{id:"3.1",name:"Three - one",children:[{id:"3.1.1",name:"Three - one - one",children:[{id:"3.1.1.1",name:"Three - one - one - one",children:[{id:"3.1.1.1.1",name:"Three - one - one - one - one"}]}]}]}]},{id:"4",name:"Four"},{id:"5",name:"Five",children:[{id:"5.1",name:"Five - one"},{id:"5.2",name:"Five - two"},{id:"5.3",name:"Five - three"},{id:"5.4",name:"Five - four"}]},{id:"6",name:"Six"}]);
const openMenuId = "3.1.1.1";
const {Component, Fragment} = React;
const {Button, Collapse, Input} = Reactstrap;
class Menu extends Component {
constructor(props) {
super(props);
this.state = {menuItems: []};
}
render() {
return <MenuItemContainer menuItems={this.state.menuItems} />;
}
componentDidMount() {
loadMenu().then(menuItems => this.setState({menuItems}));
}
}
function MenuItemContainer(props) {
if (!props.menuItems.length) return null;
const renderMenuItem = menuItem =>
<li key={menuItem.id}><MenuItem {...menuItem} /></li>;
return <ul>{props.menuItems.map(renderMenuItem)}</ul>;
}
MenuItemContainer.defaultProps = {menuItems: []};
class MenuItem extends Component {
constructor(props) {
super(props);
this.state = {isOpen: false};
this.toggle = this.toggle.bind(this);
}
render() {
let isLastChild = this.props.children ? false : true;
return (
<Fragment>
<Button onClick={this.toggle}>{this.props.name}</Button>
<Fragment>
{isLastChild ? <Input type="checkbox" value={this.props.id} /> : ''}
</Fragment>
<Collapse isOpen={this.state.isOpen}>
<MenuItemContainer menuItems={this.props.children} />
</Collapse>
</Fragment>
);
}
toggle() {
this.setState(({isOpen}) => ({isOpen: !isOpen}));
}
}
ReactDOM.render(<Menu />, document.getElementById("root"));
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/reactstrap/8.4.1/reactstrap.min.js"></script>
<div id="root"></div>
See Question&Answers more detail:os