Search code examples
reactjsreact-routerreact-redux

Apply NavItem active class for two different routes in react router.


I have a nav bar in reactJs/ router app like the following,

<Nav>
    <LinkContainer exact to="/dashboard">
        <NavItem>Dashboard</NavItem>
    </LinkContainer>
    <LinkContainer to="/contract">
        <NavItem>Contract</NavItem>
    </LinkContainer>
</Nav>

Under some cases, when the user visits /contract and for that user if there is only one contract, then the link will be redirected to /contractDetail page. When this happens, I still want my <NavItem>Contract</NavItem> to be highlighted / have active class. However, this is not working now because there is no <NavItem> for contractDetail.

I am not sure how this can be implemented, any help will be appreciated. NOTE: This is working when on the link /dashboard


Solution

  • With React-Router-Dom you can define custom logic for displaying a NavLink as active. Here's a link to the entry in the docs