Vincent
Vincent

Reputation: 5435

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?

Upvotes: 7

Views: 10510

Answers (2)

JustH
JustH

Reputation: 1402

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

Upvotes: 9

codebreach
codebreach

Reputation: 2220

You have the right idea onKeyDown or something needs to be set. Ideally I would recommend using a library like Microsoft's FabricUI or Material which do all of this behind the scenes.

Alternatively you can use react-a11y package which has checks for such things. Following is the check for onClick

https://github.com/reactjs/react-a11y/blob/master/docs/rules/click-events-have-key-events.md

Upvotes: -1

Related Questions