Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Escape NavLink path to allow special characters in path. Fixes #5584 #5596

Merged
merged 2 commits into from
Oct 6, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 27 additions & 20 deletions packages/react-router-dom/modules/NavLink.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,27 +18,34 @@ const NavLink = ({
isActive: getIsActive,
ariaCurrent,
...rest
}) => (
<Route
path={typeof to === 'object' ? to.pathname : to}
exact={exact}
strict={strict}
location={location}
children={({ location, match }) => {
const isActive = !!(getIsActive ? getIsActive(match, location) : match)
}) => {
const path = typeof to === 'object' ? to.pathname : to

return (
<Link
to={to}
className={isActive ? [ className, activeClassName ].filter(i => i).join(' ') : className}
style={isActive ? { ...style, ...activeStyle } : style}
aria-current={isActive && ariaCurrent}
{...rest}
/>
)
}}
/>
)
// Regex taken from: https://github.com/pillarjs/path-to-regexp/blob/master/index.js#L202
const escapedPath = path.replace(/([.+*?=^!:${}()[\]|/\\])/g, '\\$1')

return (
<Route
path={escapedPath}
exact={exact}
strict={strict}
location={location}
children={({ location, match }) => {
const isActive = !!(getIsActive ? getIsActive(match, location) : match)

return (
<Link
to={to}
className={isActive ? [ className, activeClassName ].filter(i => i).join(' ') : className}
style={isActive ? { ...style, ...activeStyle } : style}
aria-current={isActive && ariaCurrent}
{...rest}
/>
)
}}
/>
);
}

NavLink.propTypes = {
to: Link.propTypes.to,
Expand Down
13 changes: 13 additions & 0 deletions packages/react-router-dom/modules/__tests__/NavLink-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,19 @@ describe('NavLink', () => {
const a = node.getElementsByTagName('a')[0]
expect(a.style.color).toBe(activeStyle.color)
})

it('it properly escapes path-to-regexp special characters', () => {
ReactDOM.render((
<MemoryRouter initialEntries={['/pizza (1)']}>
<NavLink to='/pizza (1)'>Pizza!</NavLink>
</MemoryRouter>
), node)

const href = node.querySelector('a').getAttribute('href')
expect(href).toEqual('/pizza (1)')
const a = node.getElementsByTagName('a')[0]
expect(a.className).toEqual('active')
})
})

describe('When a <NavLink> is not active', () => {
Expand Down