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

React onClick handler with preventDefault() on an anchor tag does not prevent navigation #1464

Closed
amitdahan opened this issue Jun 17, 2024 · 0 comments · Fixed by #1465
Closed
Labels
bug Something isn't working

Comments

@amitdahan
Copy link
Contributor

Describe the bug

An <a href="https://example.com">Click me</a> tag with a click handler that invokes event.preventDefault() should prevent the subsequent navigation.

When doing this with pure DOM APIs:

const anchor = document.createElement('a');
anchor.href = 'http://example.com';
anchor.textContent = 'Click me';
anchor.addEventListener('click', (e) => e.preventDefault());
document.body.appendChild(anchor);

anchor.click();
expect(location.href).not.toBe('http://example.com');

This passes.

When doing the same, but passing through React (and its synthetic event handling):

render(
  <a href="http://example.com" onClick={(e) => e.preventDefault()}>
    Click me
  </a>
);

screen.getByRole('link').click();
expect(location.href).not.toBe('http://example.com');

This fails, but should pass.

To Reproduce

https://stackblitz.com/edit/stackblitz-starters-x99sjj?file=package.json

The "Pure DOM"-based test passes
The React-based one fails

Expected behavior
The React test should pass

Additional context
In real DOM and in JSDom this works as expected

@amitdahan amitdahan added the bug Something isn't working label Jun 17, 2024
amitdahan added a commit to amitdahan/happy-dom that referenced this issue Jun 17, 2024
amitdahan added a commit to amitdahan/happy-dom that referenced this issue Jun 17, 2024
capricorn86 added a commit that referenced this issue Jun 20, 2024
…tDefault

fix: [#1464] Fix react click handler with `preventDefault` on anchor not preventing navigation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
1 participant