简体   繁体   中英

Highlight active link in new react-router-dom v6

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM