Reputation: 309
I have been developing a multi-level dropdown menu component for the intranet I am building. Deciding to go with React on this I thought that I multi-level menu would be simple. Apparently not :)
What I have developed so far works quite well with one exception: When clicking on a NavLink the open menu items do not collapse.
All the CSS classes I have added are appearance only with no positioning statements. I have built this using a JSON source file and Reactstrap.
Here is the code for my component.
class MenuBar extends Component {
constructor(props) {
this.NavListItem = this.NavListItem.bind(this);
}
NavListItem = (item, level) => {
if (item.children.length > 0) {
return (
<UncontrolledDropdown direction={level!==0?"right":"down"} nav inNavbar className="menu menu-UncontrolledDropdown" key={"UCD_" + item.pageId}>
<DropdownToggle nav caret
className="menu menu-dropdown-toggle item title"
key={"DDToggle_" + item.pageId}
id={"DDToggle_" + item.pageId}
>
{item.title}
</DropdownToggle>
<DropdownMenu className="menu menu-dropdown-container">
<Nav>
{item.children.map((listItem) => this.NavListItem(listItem, level + 1))}
</Nav>
</DropdownMenu>
</UncontrolledDropdown>
)
}
else {
return (
<NavItem className="menu menu-item-container" key={"DDNavItem_" + item.pageId}>
<NavLink onClick={() => { this.props.updateCurrentPage(item) }} className="menu menu-link" key={"DDNavLink_" + item.pageId}>{item.title}</NavLink>
</NavItem>
)
}
}
render() {
const setIsOpen = (value) => {
this.setState({ isOpen: value })
}
const toggle = () => setIsOpen(!this.state.isOpen);
return (
<div className="row">
<div className="col-2 p-3 menu">
<div onClick={() => this.props.updateCurrentPage(null)}
className="align-top met-logo">
</div>
</div>
<div className="col col-md-6 offset-1 menu ">
<Navbar color="light" light expand="md" className="menu menu-bar">
<NavbarToggler onClick={toggle} className="menu menu-toggler" />
<Nav className="mr-auto" navbar>
{this.props.siteMap.siteMapData.map((link) => this.NavListItem(link, 0))}
</Nav>
</Navbar>
</div>
</div>
);
}
}
The only problem I have now is the open items do not close when an option is clicked. I would like preferably to make this stateless and put it in as a functional component ultimately but for now I am pulling Sitemap from Redux.
Thanks.
Upvotes: 1
Views: 1386
Reputation: 309
I could not find a solution but did come up with a functional workaround that takes very little resource.
In my MainComponent of the SPA I am hosting both the component as well as the current page component. What I did, when I realized that clicking off of the menu closed it, was to add a little snippet into the componentDidUpdate() function:
componentDidUpdate(){
//work around for menu not closing.
document.getElementById("rootDiv").click();
}
This effectively causes the menu to close once the new page has begun loading. Problem solved.
Upvotes: 1