From b23d7b503bf6683338755bbc263f3c254a86455f Mon Sep 17 00:00:00 2001 From: Matt Brophy Date: Wed, 2 Aug 2023 13:42:49 -0400 Subject: [PATCH] Fix docs on NavLink w.r.t. links to the root route and the end prop (#10757) * Fix docs on NavLink w.r.t. links to the root route and the end prop * Update --- docs/components/nav-link.md | 20 +++-------- .../__tests__/nav-link-active-test.tsx | 36 +++++++++++++++++++ 2 files changed, 40 insertions(+), 16 deletions(-) diff --git a/docs/components/nav-link.md b/docs/components/nav-link.md index 338abfa456..61111fe4b9 100644 --- a/docs/components/nav-link.md +++ b/docs/components/nav-link.md @@ -84,22 +84,6 @@ You can pass a render prop as children to customize the content of the `Home -``` - -To match the URL "to the end" of `to`, use `end`: - -```tsx - - Home - -``` - -Now this link will only be active at `"/"`. This works for paths with more segments as well: - | Link | URL | isActive | | ----------------------------- | ------------ | -------- | | `` | `/tasks` | true | @@ -107,6 +91,10 @@ Now this link will only be active at `"/"`. This works for paths with more segme | `` | `/tasks` | true | | `` | `/tasks/123` | false | +**A note on links to the root route** + +`` is an exceptional case because _every_ URL matches `/`. To avoid this matching every single route by default, it effectively ignores the `end` prop and only matches when you're at the root route. + ## `caseSensitive` Adding the `caseSensitive` prop changes the matching logic to make it case sensitive. diff --git a/packages/react-router-dom/__tests__/nav-link-active-test.tsx b/packages/react-router-dom/__tests__/nav-link-active-test.tsx index c288f2e548..8e597acc48 100644 --- a/packages/react-router-dom/__tests__/nav-link-active-test.tsx +++ b/packages/react-router-dom/__tests__/nav-link-active-test.tsx @@ -317,6 +317,42 @@ describe("NavLink", () => { expect(anchors.map((a) => a.props.className)).toEqual(["active", ""]); }); + it("matches the root route with or without the end prop", () => { + let renderer: TestRenderer.ReactTestRenderer; + TestRenderer.act(() => { + renderer = TestRenderer.create( + + + Root} /> + + + ); + }); + + let anchor = renderer.root.findByType("a"); + expect(anchor.props.className).toMatch("active"); + + TestRenderer.act(() => { + renderer = TestRenderer.create( + + + + Root + + } + /> + + + ); + }); + + anchor = renderer.root.findByType("a"); + expect(anchor.props.className).toMatch("active"); + }); + it("does not automatically apply to root non-layout segments", () => { let renderer: TestRenderer.ReactTestRenderer; TestRenderer.act(() => {