简体   繁体   中英

ReactJS NavLink activeClassName

I want to rendered a NavLink with a active class when the route is the same that the current route. This is the code:

<NavLink className="nav-link-gdc" activeClassName="nav-link-gdc-selected" to="/home">HOME</NavLink>

The problem is that this only works when I reload the URL and I do not know how to trigger the change of the class when I click in the link.

EDIT:

My entry point:

ReactDOM.render(
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <div>
        <HeaderControl />
        <MuiThemeProvider>
          <Switch>
            <Routes />
            <PrivateRoute path="/" component={Home} />
          </Switch>
        </MuiThemeProvider>
        <Footer />
      </div>
    </ConnectedRouter>
  </Provider>,
  document.getElementById('app'),
);

All the links that I want to change the class when active are in the HeaderControl. How could I use the prop location ?

Any ideas?

You could do something like:

<NavLink className="nav-link-gdc" activeClassName={location.pathname !== "your pathname"? null : "nav-link-gdc-selected"} to="/home">HOME</NavLink>

Or don't I get your problem?

Anybody looking in 2022+, the latest version of react-router-dom (currently 6.3.0 a the time of writing) has deprecated the NavLink activeClassName . Instead, now, a callback function can be passed to className prop to pass in an active class style. No more need for location .

<NavLink 
  className={nav => (nav.isActive ? "main-nav-link active" : "main-nav-link")} 
  to="/"
>
  Home
</NavLink

You can see that an argument is provided to that function with an isActive property. The truthiness of this property can be used to dynamically add class names.


But a version with location could be done like this:

import { useLocation, NavLink } from 'react-router-dom'

const NavBar = () => {
  const location = useLocation()
    
  return (
    <NavLink 
      className={location.pathname === "/" ? "main-nav-link active" : "main-nav-link")} 
      to="/"
    >
      Home
    </NavLink>
  )
}

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