Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make an accessible onClick handler for links in React?

I have a link in my React application that calls an onClick handler as follows:

<a onClick={handleClick}>Link</a>

However, since I'm not using the native href attribute, this handler does not get activated when I focus the link, then press Enter.

Now, of course I could add an onKeyDown handler, then check whether the key that was pressed is Space or Enter and, if it is, call handleClick. However, I'm afraid that that won't be enough to capture all accessibility nuances, nor whether it will behave exactly like regular links.

Thus, the question is: is there a way to indicate that I want my function to be called when the link is followed by whatever possible interaction method?

like image 322
Vincent Avatar asked Jan 02 '19 14:01

Vincent


1 Answers

an <a> tag without an href is no longer valid. Instead of trying to reimplement focus and keyboard logic, use a button and style however you like. Semantically, if it is firing an onClick it should most likely be a button and will be most accessible.

For reference https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/anchor-is-valid.md

like image 100
JustH Avatar answered Nov 06 '22 13:11

JustH