Reputation: 426
I am using React Pro Sidebar navigation (https://github.com/azouaoui-med/react-pro-sidebar) and I am not too sure how to set the active
prop on a selected menu item from a menu that has multiple links.
code:
<SidebarContent>
<Menu iconShape="square">
<MenuItem icon={<IoHomeOutline />}>
Home
<Link to="/home" />
</MenuItem>
<MenuItem icon={<IoPeopleOutline />}>
HighSev OnCalls
<Link to="/oncalls" />
</MenuItem>
<MenuItem icon={<IoCellularOutline />}>
Reports
<Link to="/reports" />
</MenuItem>
</Menu>
</SidebarContent>;
TIA
Upvotes: 0
Views: 4897
Reputation: 480
I've replaced direct usage of window.location
with the useLocation()
hook from react-router-dom
. It's straightforward to integrate into a React router app. One issue I encountered was related to nested routes where the exact match check didn't cover all scenarios. For example, if the current route is /home/details
, the sidebar wouldn't reflect the active state for /home/
. To resolve this, I assigned unique keys to each sidebar item and checked whether they were present in the URL. This approach allowed me to ensure sidebar items reflected their active state accurately regardless of nested routes.
import { Link, useLocation } from 'react-router-dom';
const location = useLocation();
{item.menuItems.map((menuItem) => (
<MenuItem
active={location.pathname.includes(menuItem.key)}
className={classes.sidebarMenuItem}
key={menuItem.key}
icon={menuItem.icon}
component={<Link to={menuItem.url} />}
>
{menuItem.name}
</MenuItem>
))}
Upvotes: 1
Reputation: 839
On the documentation itself has defined prop active
on MenuItem
#UPDATED
Check if your current path is same as link's path then set that MenuItem
to active
. Same for other items too.
<MenuItem active={window.location.pathname === "/home/"} icon={<IoHomeOutline />}>
Home
<Link to="/home" />
</MenuItem>
Upvotes: 4