Skip to content

Commit 7038143

Browse files
committed
[ButtonBase] Ensure that onClick propagates when non-native button is clicked
1 parent b2332e5 commit 7038143

2 files changed

Lines changed: 42 additions & 5 deletions

File tree

packages/mui-material/src/ButtonBase/ButtonBase.js

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -219,9 +219,7 @@ const ButtonBase = React.forwardRef(function ButtonBase(inProps, ref) {
219219
!disabled
220220
) {
221221
event.preventDefault();
222-
if (onClick) {
223-
onClick(event);
224-
}
222+
event.currentTarget.click();
225223
}
226224
});
227225

@@ -239,13 +237,12 @@ const ButtonBase = React.forwardRef(function ButtonBase(inProps, ref) {
239237

240238
// Keyboard accessibility for non interactive elements
241239
if (
242-
onClick &&
243240
event.target === event.currentTarget &&
244241
isNonNativeButton() &&
245242
event.key === ' ' &&
246243
!event.defaultPrevented
247244
) {
248-
onClick(event);
245+
event.currentTarget.click();
249246
}
250247
});
251248

packages/mui-material/src/ButtonBase/ButtonBase.test.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,46 @@ describe('<ButtonBase />', () => {
247247
fireEvent.mouseLeave(button);
248248
expect(onMouseLeave.callCount).to.equal(1);
249249
});
250+
251+
it('should propagate click events when Enter is pressed on non-native button', async () => {
252+
const parentClickSpy = spy();
253+
const buttonClickSpy = spy();
254+
255+
const {user} = render(
256+
<div onClick={parentClickSpy}>
257+
<ButtonBase onClick={buttonClickSpy} component="div">
258+
Hello
259+
</ButtonBase>
260+
</div>,
261+
);
262+
263+
// moves focus to the button
264+
await user.tab()
265+
await user.keyboard('{Enter}');
266+
267+
expect(buttonClickSpy.callCount).to.equal(1);
268+
expect(parentClickSpy.callCount).to.equal(1);
269+
});
270+
271+
it('should propagate click events when Space is released on non-native button', async () => {
272+
const parentClickSpy = spy();
273+
const buttonClickSpy = spy();
274+
275+
const {user} = render(
276+
<div onClick={parentClickSpy}>
277+
<ButtonBase onClick={buttonClickSpy} component="div">
278+
Hello
279+
</ButtonBase>
280+
</div>,
281+
);
282+
283+
// moves focus to the button
284+
await user.tab();
285+
await user.keyboard(' ');
286+
287+
expect(buttonClickSpy.callCount).to.equal(1);
288+
expect(parentClickSpy.callCount).to.equal(1);
289+
});
250290
});
251291

252292
describe.skipIf(isJsdom())('ripple', () => {

0 commit comments

Comments
 (0)