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

Time:12-07

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

CodePudding user response:

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>

CodePudding user response:

Here is an example of how NavLink work with activeClassName

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related