mvovchak mvovchak -4 years ago 296
React JSX Question

Set active class with react-router Link that has an optional URL parameter

How can I set the active class name of a Link for a path that contains an optional parameter?

Below are some details of what I am trying to achieve:

  • A route in my application has a path that contains an optional URL parameter - eventId:

    <Route path="/sendInvite(/:eventId)" component={SendInviteContainer} />

  • In my main navigation component there is a
    that points to /sendInvite path (without the optional param):

    <Link to="/sendInvite" activeClassName="active">Send Invite</Link>

If the user accesses the path
, the Link has now an active class set, which is the correct behaviour for this case.

However, when the user accesses
, the Link in my navigation that points to /sendInvite has no active class set.

Any ideas on how to set the Link to active with the optional parameter in the address bar?

Answer Source

You need to put you /sendInvite(/:eventId) under /sendInvite route

It should be something like this:-

<Route path="/sendInvite" component={container} >
     <Route path="/sendInvite(/:eventId)" component={SendInviteContainer} />

This should keep you parent route active.

You can check out here, check for how users part is taken care off in router, it would solve your purpose.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download