reactjsaccessibilityreact-aria

react-aria useButton hook disabling accessibility functionality rather than supporting it


I'm integrating the react-aria hook library into my codebase to ensure that my custom components properly meet all ARIA accessibility requirements. I've immediately noticed however that when I use the props generated by the library's useButton hook as described in the documentation, that a button which was focused with Tab no longer executes its onClick event on key press of Enter or Space, functionality that previously worked just fine before integration of the library.

The below sandbox illustrates the issue: Tabbing to the green button (the RegularButton component) and pressing Enter or Space will fire the onClick event and render the message. However, toggling to the red button (the ButtonWithReactAria component) and pressing Enter or Space will result in nothing happening.

https://codesandbox.io/p/sandbox/twilight-cloud-np66r3

Does anyone know what's causing this issue?


Solution

  • From the documentation

    useButton supports user interactions via mouse, keyboard, and touch. You can handle all of these via the onPress prop. This is similar to the standard onClick event, but normalized to support all interaction methods equally.

    So all you need to do is change the onClick prop passed to your ButtonWithReactAria component to onPress, and all will be well. See this forked sandbox where I've done exactly that (and made no other changes), and the button now works as expected with both keybord and mouse.

    (I notice this is a Typescript codesandbox so it's a fair question to ask why Typescript isn't preventing you using the wrong prop here. I can't answer that without delving quite deeply into the types involved, since I'm not personally very familiar with react-aria. It's certainly unfortunate that TS doesn't seem to protect you from this error. But I'm prioritising getting this answer out there!)