Anuja Nimesh
Anuja Nimesh

Reputation: 422

Need to apply "active" class when in a exact link to NavLink in react router V6

React router automatically applies "active" className even to non exact links.
I only need it to give the NavLink the "active" class when the user is in /solutions/
But when the user is in /solutions/web_apps, it still gives the NavLink the "active" class.

Here's my nav:

<nav>
    <div>
        <NavLink to="/"></NavLink>
    </div>
    <ul>
        <NavLink to="/about">about</NavLink>
        <NavLink to="/promises">our promise</NavLink>
        <NavLink to="/process">our process</NavLink>
        <NavLink exact={true} to="/solutions">solutions</NavLink>
        <NavLink to="/careers">careers</NavLink>
    </ul>
    <NavLink to="/letstalk">let's talk</NavLink>
</nav>

This is the link to /solutions/web_apps

<Link exact={true} to="/solutions/web_apps">
    <h3>...</h3><p>...</p>
</Link>

Here are the Routes:

<Routes>
    <Route exact={true} path="/" element={<Home />} />
    <Route exact={true} path="/solutions" element={<Solutions />} />
    <Route exact={true} path="/solutions/web_applications/" element={<WebApps />} />
    ...
</Routes>

How can I give the "active" className to NavLink only when I'm in /solutions/ and not when I'm in /solutions/web_apps or in any link inside /solutions/
Please don't recommend downgrading

Thanks in advance

Upvotes: 1

Views: 4639

Answers (1)

Drew Reese
Drew Reese

Reputation: 202751

The exact prop doesn't exist in the RRDv6 APIs for the most part. I think you're looking for the NavLink's end prop.

NavLink

declare function NavLink(
  props: NavLinkProps
): React.ReactElement;

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);
}

From the docs (emphasis mine):

If the end prop is used, it will ensure this component isn't matched as "active" when its descendant paths are matched. For example, to render a link that is only active at the website root and not any other URLs, you can use:

<NavLink to="/" end>
  Home
</NavLink>

Add the end prop to the nav links you only want matched as "active" for the path specified.

<nav>
  <div>
    <NavLink to="/"></NavLink>
  </div>
  <ul>
    <NavLink to="/about">about</NavLink>
    <NavLink to="/promises">our promise</NavLink>
    <NavLink to="/process">our process</NavLink>
    <NavLink to="/solutions" end>solutions</NavLink>
    <NavLink to="/careers">careers</NavLink>
  </ul>
  <NavLink to="/letstalk">let's talk</NavLink>
</nav>

Upvotes: 5

Related Questions