Skip to content

Commit 2d80151

Browse files
committed
Automatically escape paths in <NavLink>
I removed this earlier in f5f2107 but realized that was a bad move because it would be a breaking change. Also, we probably need this since <NavLink to> serves as both the <Route path> *and* the <Link to> value. Maybe we should have a separate prop for <NavLink path>? I dunno.
1 parent 3bac92e commit 2d80151

File tree

2 files changed

+9
-3
lines changed

2 files changed

+9
-3
lines changed

packages/react-router-dom/modules/NavLink.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,14 @@ function NavLink({
2424
to,
2525
...rest
2626
}) {
27+
const path = typeof to === "object" ? to.pathname : to;
28+
29+
// Regex taken from: https://github.com/pillarjs/path-to-regexp/blob/master/index.js#L202
30+
const escapedPath = path && path.replace(/([.+*?=^!:${}()[\]|/\\])/g, "\\$1");
31+
2732
return (
2833
<Route
29-
path={typeof to === "object" ? to.pathname : to}
34+
path={escapedPath}
3035
exact={exact}
3136
strict={strict}
3237
location={location}

packages/react-router-dom/modules/__tests__/NavLink-test.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,17 +99,18 @@ describe("A <NavLink>", () => {
9999
}).not.toThrow();
100100
});
101101

102-
it("it handles properly escaped special characters", () => {
102+
it("it automatically escapes special characters in the path", () => {
103103
ReactDOM.render(
104104
<MemoryRouter initialEntries={["/pizza (1)"]}>
105-
<NavLink to="/pizza \(1\)">Pizza!</NavLink>
105+
<NavLink to="/pizza (1)">Pizza!</NavLink>
106106
</MemoryRouter>,
107107
node
108108
);
109109

110110
const a = node.querySelector("a");
111111

112112
expect(a.className).toContain("active");
113+
expect(a.getAttribute("href")).toEqual("/pizza (1)");
113114
});
114115

115116
it("renders child components that use withRouter", () => {

0 commit comments

Comments
 (0)