Павел Родин
Павел Родин

Reputation: 51

active state doesn't work for my NavLink but inline style is OK

So the problem is I do something wrong cause active class doesn't work. Here is what it looks like enter image description here

inline style is working perfect but "activeClassName" isn't. That's my modules.css enter image description here

And what I see in browser is enter image description here

Upvotes: 2

Views: 1373

Answers (2)

Sabrina Luo
Sabrina Luo

Reputation: 4010

Here is an example of how NavLink work with activeClassName in v5.x

const NavLink = ReactRouterDOM.NavLink;
const Route = ReactRouterDOM.Route;
const arr = ['a','b','c']
const App = () => <ReactRouterDOM.HashRouter>
  {arr.map(s=> 
    <NavLink key={s} to={`/${s}`} activeClassName="active">link {s}</NavLink>
  )}
  </ReactRouterDOM.HashRouter >;

ReactDOM.render( < App / > , document.querySelector('#app'));
a:link,
a:visited,
a:hover {
  color: blue;
}

a.active {
  color: red;
}

a {
  display: inline-block;
  padding: 0 8px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-router-dom.min.js"></script>

<div id="app">

</div>

Upvotes: 1

Drew Reese
Drew Reese

Reputation: 203466

The NavLink API changed a bit in react-router-dom v6, there is no longer an activeClassName prop.

NavLink

interface NavLinkProps
  extends Omit<LinkProps, "className" | "style"> {
  caseSensitive?: boolean;
  className?:
    | string
    | ((props: { isActive: boolean }) => string);
  end?: boolean;
  style?:
    | React.CSSProperties
    | ((props: {
        isActive: boolean;
      }) => React.CSSProperties);
}

You can conditionally apply your active class via a className prop function, or in the style prop function.

<NavLink
  className={({ isActive }) => isActive ? s.active : null}
  to={props.buttonName.toLowerCase()}
>
  {props.buttonName}
</NavLink>

Upvotes: 2

Related Questions