Skip to content

Commit

Permalink
fix: respect the replace prop if it is defined (#8779)
Browse files Browse the repository at this point in the history
* Fix: respect the replace prop if it is defined

* Update contributors.yml
  • Loading branch information
williamsdyyz committed Jun 7, 2022
1 parent 9b8ce54 commit 7278f79
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 3 deletions.
2 changes: 2 additions & 0 deletions contributors.yml
Expand Up @@ -63,4 +63,6 @@
- turansky
- underager
- vijaypushkin
- rtmann
- williamsdyyz
- vikingviolinist
61 changes: 61 additions & 0 deletions packages/react-router-dom/__tests__/link-push-test.tsx
Expand Up @@ -222,4 +222,65 @@ describe("Link push and replace", () => {
`);
});
});

describe("to the same page with replace={false}, when it is clicked", () => {
it("performs a push", () => {
function Home() {
return (
<div>
<h1>Home</h1>
<Link to="." replace={false}>
Home
</Link>
<ShowNavigationType />
</div>
);
}

function About() {
return <h1>About</h1>;
}

let renderer: TestRenderer.ReactTestRenderer;
TestRenderer.act(() => {
renderer = TestRenderer.create(
<MemoryRouter initialEntries={["/home"]}>
<Routes>
<Route path="home" element={<Home />} />
<Route path="about" element={<About />} />
</Routes>
</MemoryRouter>
);
});

let anchor = renderer.root.findByType("a");

TestRenderer.act(() => {
anchor.props.onClick(
new MouseEvent("click", {
view: window,
bubbles: true,
cancelable: true,
})
);
});

expect(renderer.toJSON()).toMatchInlineSnapshot(`
<div>
<h1>
Home
</h1>
<a
href="/home"
onClick={[Function]}
>
Home
</a>
<p>
PUSH
</p>
</div>
`);
});
});
});
8 changes: 5 additions & 3 deletions packages/react-router-dom/index.tsx
Expand Up @@ -343,7 +343,7 @@ export const Link = React.forwardRef<HTMLAnchorElement, LinkProps>(
{
onClick,
reloadDocument,
replace = false,
replace,
state,
target,
to,
Expand Down Expand Up @@ -641,9 +641,11 @@ export function useLinkClickHandler<E extends Element = HTMLAnchorElement>(
event.preventDefault();

// If the URL hasn't changed, a regular <a> will do a replace instead of
// a push, so do the same here.
// a push, so do the same here unless the replace prop is explcitly set
let replace =
!!replaceProp || createPath(location) === createPath(path);
replaceProp !== undefined
? replaceProp
: createPath(location) === createPath(path);

navigate(to, { replace, state, resetScroll });
}
Expand Down

0 comments on commit 7278f79

Please sign in to comment.