3

I need to highlight the active NavLink in react-router v6. It states in the docs (https://v5.reactrouter.com/web/api/NavLink) that we need to stop using className and instead go with an inline style function, but I cannot figure it out properly. Here is the code sandbox: https://codesandbox.io/s/router-v6-highlight-active-link-c50bo?file=/src/Home.jsx

Basically the code below shows how the docs tell us to do it, but it seems not to work for me.

          <NavLink 
            to='search' 
            className='navlinkbuttons'
            style={isActive => ({
              color: isActive ? "green" : "blue"
            })}
            >
              Search
          </NavLink>

All help is appreciated. Thanks!

OMGItsRob
  • 105
  • 1
  • 2
  • 7
  • Basic gist, `isActive` is a destructured property now, i.e. `({ isActive }) => isActive ? .... : ....` instead of `(isActive) => isActive ? .... : ....`. – Drew Reese Jan 03 '22 at 23:58
  • all you have to do is define the `.active` class, and it just works – toddmo Feb 01 '23 at 22:20

1 Answers1

8

NavLink activeClassName prop does not exists anymore in V6. You have to do it manually like followings :

 <NavLink
    className={(navData) => (navData.isActive ? 'active' : '')}
    to="/child"
  >
    menu 1
  </NavLink>

Working example : https://stackblitz.com/edit/react-pdudcd?file=src/Navigation.js

programoholic
  • 4,830
  • 5
  • 20
  • 59