4.0.0
<Link to='/agent' isActiveClass='active'>Agent</Link>
<Link to='/agent-code' isActiveClass='active'>Agent Code</Link>
<Match pattern="/agent" render={() => <div>Agent Path</div>}/>
<Match pattern="/agent-code" render={() => <div>Agent Code Path</div>}/>
Open /agent. Only the first path and link is 'Matched'/active.
Go to /agent-code. Only the second path and link should be 'Matched'/active
Open /agent. Only the first path and link is 'Matched'/active.
Go to /agent-code. Only the second path is 'Matched'. Both Links are 'active'.
I fixed this locally using the following piece of code:
const pathIsActive = (to, pathname, activeOnlyWhenExact) => activeOnlyWhenExact ? pathname === to : new RegExp(to.replace(/(\/|\?)/ig, '\\$1') + '(\\/|\\?|#|$)').test(pathname)
Note that I do not want to use the exact matching as in my real case I have two more routes: /agent/:agentId and /agent-code/:agentCodeId that should still show the above Links as being active.
Good catch. One minor change is that because pathIsActive is only testing against the pathname, the regex should only have to check if the pathname is followed by a forward slash or the end of the string.
A PR with some test cases would be helpful.
(Also, I believe you meant activeClassName not isActiveClass in your example.)
I'll see if I can do a PR tomorrow. I had a brief look and couldn't figure out how to write the tests, I should have enough time tomorrow.
Thanks for the regex tip, I forgot it's only the pathname which is simpler to check.
Check out the isActive section in Link-test.js.
PR Created with tests!
Thanks for your work here, @SimeonC, and for bringing this to our attention. Let's follow up in https://github.com/ReactTraining/react-router/pull/4357.
Most helpful comment
PR Created with tests!