Skip to content

Instantly share code, notes, and snippets.

@bogas04
Last active March 12, 2020 08:29
Show Gist options
  • Save bogas04/da75f9232734c7ef828bd6cce5da1302 to your computer and use it in GitHub Desktop.
Save bogas04/da75f9232734c7ef828bd6cce5da1302 to your computer and use it in GitHub Desktop.
Accessibility Tips

Accessibility

Had a discussion with Rahul Dhawani about a11y. The solution to the linter telling you to add tabIndex/onKeyDown/role isn't to follow it (lol), but to evaluate whether we need a button here or an anchor, or we simply need to wrap the inner callback with our function. Linter doesn't know what is your usecase, so it tries best to make your div accessible, but that's just patch work. Before I share suggestions, I would like to share why we should care:

Makes customers happy

  • Someone using a keyboard, a screen reader or with some disability would be happy you cared for them.

Free benefits by using HTML properly!

  • Element focus without any handlers
  • Keyboard & screen reader accessibility
  • Needs no/less JS which is better for TTI
  • Less DOM elements usually
  • Anchor tags work with JS disabled

Avoids legal issues

Some common examples:

Div as an anchor

BAD:

<div onClick={this.goToHome} />

GOOD:

<a href={Routes.HOME} onClick={this.handleAnalyticsForHomeClick}
/>

You really want to use an anchor here. Pros: It's automatically focussable, would work with keyboard & a screen reader, and in case of no javascript (SSR/SEO) it would know how to handle the tap.

Div as scroll to top

BAD:

<div onClick={this.goToHome} />

GOOD:

<a href="#id-of-element-to-scroll-to"></a>

You really want to use an anchor here and rely on browser to handle scrolling without JS. Pros: It's automatically focussable, would work with keyboard & a screen reader, and in case of no javascript (SSR/SEO) it would know how to handle the tap.

Div as a button

BAD:

<div onClick={this.onAddClick} />

GOOD:

<button onClick={this.onAddClick} />

You really want to use a button here. Pros: It's automatically focussable, would work with keyboard & a screen reader.

Div as an click trapper

BAD:

<div onClick={this.handleClick}>   <button onClick={     this.props.onAddClick   }>     Add   </button>
</div>

GOOD:

<button onClick={(e) => {   this.handleClick();   this.props.onAddClick(e);   }}>   Add
</button>

You really want to wrap onAddClick. If you follow linter you'll end up with nested buttons and weird things getting focussed. Pros: less stuff on DOM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment