Open OliverJAsh opened 4 years ago
If removing preventDefault()
is not a suitable option, using onKeyPress
or onKeyUp
event is preferable as it will comply with WCAG 2.1 Success Criterion 2.5.2 Pointer Cancellation so users will not be able to activate it by mistake (including when scrolling on touch screens as it also fires onKeyDown
event) and assistive technology (i.e. screen readers and speech-to-text) will be able to activate the control as well.
UPD: Also, for button
elements both event.keyCode === 13
(for Enter) and event.keyCode === 32
(for Space) needs to be used. Otherwise, keyboard navigation with Tab and Tab+Shift (or Up/Down arrows) will trigger the event.
Workaround: pass onKeyDown={undefined}
. Reduced test case: https://stackblitz.com/edit/react-ts-fnndrm?file=index.tsx
Reduced test case: https://stackblitz.com/edit/react-ts-sbkech?file=index.tsx
If you open the menu, focus the
a
, and then press enter, the customonClick
handler is fired as seen from the logs. ✅If you open the menu, focus the
button
, and then press enter, the customonClick
handler is not fired as seen from the logs. ❌I would expect
onClick
to work when the user presses enter on abutton
, just like how it works on ana
.My understanding of what is happening here:
MenuItem
has some code that willpreventDefault
inside thekeydown
event if this condition is not met:this.props.tag === 'a' && this.props.href
tag
isbutton
, it willpreventDefault
click
event after thekeydown
event finishesNote:
onClick
is called if you actually click, as opposed to using the enter key.