React-router: Problem with similarly named routes

Created on 2 Nov 2016  路  5Comments  路  Source: ReactTraining/react-router

Version

4.0.0

Test Case

<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>}/>

Expected Behavior

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

Actual Behavior

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.

bug

Most helpful comment

PR Created with tests!

All 5 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sarbbottam picture sarbbottam  路  3Comments

tomatau picture tomatau  路  3Comments

winkler1 picture winkler1  路  3Comments

alexyaseen picture alexyaseen  路  3Comments

ArthurRougier picture ArthurRougier  路  3Comments