Redwood "NavLink" with antd

I was looking at using antd for the current project. The current small snag is antd sets the “active” link on the wrapping Menu component. Is there an easy way to get the currently active routes name?

At the moment I’m specifying the key of each menu item to match the route name so this should solve the “problem” if that is doable.

The useLocation() hook may help:

import { useLocation } from '@redwoodjs/router'

Then can look at location.pathname and compare against the path in your menu link?

More info on NavLink here:

2 Likes

Here’s what we’re doing

  const navKeyFromPathName = location.pathname.split('/')[2] || 'dashboard'

and where you use the menu, pass it along

        <Menu
          theme="dark"
          mode="inline"
// here -> 
          selectedKeys={navKeyFromPathName}
          onClick={navigateFromMenu}
        >
              <Menu.Item key="profile">Profile</Menu.Item>
...
.

Our paths look like /dashboard, /dashboard/profile, /dashboard/tokens, etc. Also useLocation may be better, I’d written this all the way back in RW 0.6

Just a headsup, if you’re not commited to using antd, it can be quite heavy. See our live bundle here https://tape.sh/bundle-analyzer-output.html I’ve tried various optimisations, but short of individually eliminating modules, I couldn’t get antd much smaller.

Please do let me know if you find a way around this.

1 Like

One thing I do for my menu is make sure child elements also set the parent to highlight.

const validRoutes = [routes.user({ id: currentUser.id }), routes.settings()]
const isActive = () => validRoutes.some((route) => useMatch(route).match)

Then I use the isActive boolean to add a class to the root menu item.

<Menu display={displayMenu} className={`${isActive && 'text-purple-900'}`}>
  <MenuItem route={routes.user({ id: currentUser.id })}>
    Profile
  </MenuItem>
  <MenuItem route={routes.settings()}>Settings</MenuItem>
</Menu>

Then each MenuItem also checks if it is active using the exact method @dthyresson showed.