Skip to content

Commit 5100ed6

Browse files
authored
fix: don't prevent default on button clicks (#33)
1 parent c1f0a3c commit 5100ed6

File tree

3 files changed

+51
-2
lines changed

3 files changed

+51
-2
lines changed

src/Anchor.tsx

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,11 @@
44
import * as React from 'react';
55

66
import { useEventCallback } from '@restart/hooks';
7-
import { useButtonProps, isTrivialHref } from './Button';
7+
import { useButtonProps } from './Button';
8+
9+
export function isTrivialHref(href?: string) {
10+
return !href || href.trim() === '#';
11+
}
812

913
export interface AnchorProps extends React.HTMLAttributes<HTMLElement> {
1014
href?: string;

src/Button.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ export function useButtonProps({
6161
}
6262

6363
const handleClick = (event: React.MouseEvent | React.KeyboardEvent) => {
64-
if (disabled || isTrivialHref(href)) {
64+
if (disabled || (tagName === 'a' && isTrivialHref(href))) {
6565
event.preventDefault();
6666
}
6767

test/ButtonSpec.tsx

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,51 @@ describe('<Button>', () => {
101101
expect(clickSpy).to.have.not.been.called;
102102
});
103103

104+
// eslint-disable-next-line mocha/no-setup-in-describe
105+
['#', ''].forEach((href) => {
106+
it(`should prevent default on trivial href="${href}" clicks`, () => {
107+
const clickSpy = sinon.spy();
108+
109+
const { getByText } = render(
110+
<div onClick={clickSpy}>
111+
<Button href={href}>Title</Button>
112+
</div>,
113+
);
114+
115+
const button = getByText('Title');
116+
117+
expect(button).to.exist;
118+
119+
fireEvent.click(button);
120+
121+
expect(clickSpy).to.have.been.called;
122+
const event = clickSpy.getCall(0).args[0];
123+
124+
expect(event.defaultPrevented).to.equal(true);
125+
});
126+
});
127+
128+
it(`should not prevent default on button clicks`, () => {
129+
const clickSpy = sinon.spy();
130+
131+
const { getByText } = render(
132+
<div onClick={clickSpy}>
133+
<Button>Title</Button>
134+
</div>,
135+
);
136+
137+
const button = getByText('Title');
138+
139+
expect(button).to.exist;
140+
141+
fireEvent.click(button);
142+
143+
expect(clickSpy).to.have.been.called;
144+
const event = clickSpy.getCall(0).args[0];
145+
146+
expect(event.defaultPrevented).to.equal(false);
147+
});
148+
104149
it('Should be disabled link', () => {
105150
const clickSpy = sinon.spy();
106151

0 commit comments

Comments
 (0)