I needed some help spawning multi-level dropdowns in the React-bootstrap navbar with Maps.
I have a constant.js file that contains all the data that I want to dynamically populate in the NavBar dropdown
export const navLinks = [
{
id: "transactions",
title: "Transactions",
children: [
{
id: 'transactions/LotAssignment',
title: 'Lot Assignment Maintenance',
component: <LotAssignmentMaintenance />
},
{
id: 'transactions/ShopOrder',
title: 'Shop Order Maintenance',
children: [
{
id: 'shopOrder/Print',
title: 'Shop Order Print',
component: <ShopPrint />
},
]
},
{
id: 'transactions/Lot',
title: 'Lot Maintenance',
component: <LotMaintenance />
}
]
},
];
Notice that it still has children data inside the children, which I want to output into a multi-level dropdown
and then, I have the below component called Navigation.jsx which I use Map to create the Navbar dropdown
import React from "react";
import { Navbar, Nav, Container, NavDropdown } from "react-bootstrap";
import { navLinks } from "../constants/index.js";
import { Route, Routes, Link, BrowserRouter } from "react-router-dom";
export const Navigation = () => {
return (
<BrowserRouter>
<Navbar bg="dark" variant="dark" expand="lg">
<Container>
<Navbar.Brand as={Link} to="/"></Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="ms-auto">
{navLinks.map((nav, index) => {
if (!nav.children) {
return (
<Nav.Link as={Link} to={`${nav.id}`} key={nav.id}>
{nav.title}
</Nav.Link>
);
} else if (nav.children) {
console.log(nav.children.child);
return (
<NavDropdown
key={nav.id}
title={nav.title}
id="basic-nav-dropdown"
>
{nav.children.map((dropdown, idx) => (
<NavDropdown.Item
key={dropdown.id}
as={Link}
to={`${dropdown.id}`}
>
{dropdown.title}
</NavDropdown.Item>
))}
</NavDropdown>
);
} else {
}
})}
</Nav>
</Navbar.Collapse>
</Container>
</Navbar>
<Routes>
{navLinks.map((nav, index) => {
if (!nav.children) {
return <Route path={nav.id} element={nav.component} key={nav.id} />;
} else {
return nav.children.map((child, idx) => (
<Route path={child.id} element={child.component} key={child.id} />
));
}
})}
</Routes>
</BrowserRouter>
);
};
the code output is below
The problem is, for the part that still has children,
the dropdown is not created, the expected output is like below.
Thanks in Advance 🙂