Skip to content

Commit

Permalink
Merge pull request #1465 from amitdahan/fix-anchor-react-click-preven…
Browse files Browse the repository at this point in the history
…tDefault

fix: [#1464] Fix react click handler with `preventDefault` on anchor not preventing navigation
  • Loading branch information
capricorn86 committed Jun 20, 2024
2 parents ef2dfea + a3b6d86 commit 8da51ee
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -500,8 +500,7 @@ export default class HTMLAnchorElement extends HTMLElement implements IHTMLHyper
if (
event.type === 'click' &&
event instanceof MouseEvent &&
(event.eventPhase === EventPhaseEnum.atTarget ||
event.eventPhase === EventPhaseEnum.bubbling) &&
event.eventPhase === EventPhaseEnum.none &&
!event.defaultPrevented
) {
const href = this.href;
Expand Down
10 changes: 10 additions & 0 deletions packages/jest-environment/test/react/React.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -110,4 +110,14 @@ describe('React', () => {
await TESTING_LIBRARY_USER.click(button);
expect(document.querySelector('p span').textContent).toBe('test');
});

it('Can `preventDefault` to prevent navigation with React click listener on an anchor tag', async () => {
location.href = 'http://localhost/';
const { getByRole } = ReactTestingLibrary.render(
<a href="http://example.com" onClick={(ev) => ev.preventDefault()} />
);
expect(document.location.href).toBe('http://localhost/');
await TESTING_LIBRARY_USER.click(getByRole('link'));
expect(document.location.href).toBe('http://localhost/');
});
});

0 comments on commit 8da51ee

Please sign in to comment.