0.1.0 • Published 5 years ago

unbutton v0.1.0

Weekly downloads
3
License
MIT
Repository
github
Last release
5 years ago

🖱 Unbutton

NPM version Build status Code coverage Bundle size Bundle size

React component to add onClick to HTML elements without sacrificing accessibility.

What is this?

It's very hard to remove all styles from HTML button elements. It's also hard to create clickable divs that are accessible. This can cause developers to ship inaccessible UI.

The Unbutton React component accepts an onClick prop and an element to render. It returns the element with the onClick as well as the attributes and event listeners needed to make it as accessible as a button.

Install

You can install Unbutton with NPM or Yarn.

npm install unbutton --save-exact
yarn add unbutton --exact

We encourage pinning the version number until Unbutton reaches 1.0.0. We may ship breaking changes in 0.x.x versions.

Usage

Here's how to use Unbutton to make a clickable SVG:

// import Unbutton from 'unbutton';

<Unbutton
  onClick={this.closeModal}
  aria-label="Close modal"
  className="icon-button"
>
  <CloseIcon />
</Unbutton>

Unbutton will return a span that looks like this:

<span
  // Make the element clickable
  onClick={this.closeModal}
  // Make the element navigable by keyboard
  tabIndex={0}
  // Call `this.closeModal` if the user presses either the
  // enter or space key while the element is in focus
  onKeyDown={...}
  // Tell screen readers that the element is a button
  role="button"
  // Indicate on hover that the element is clickable
  style={{ cursor: 'pointer' }}
  // All other props are passed through to the element
  aria-label="Close modal"
  className="icon-button"
>
  <CloseIcon />
</span>

The resulting HTML is accessible for users navigating by screen readers, keyboard, and mouse/touch.

Props

There are a few props that are built into Unbutton:

proptypedescription
onClickfunction | defaults to: undefinedThe action to perform when the element is pressed
isstring, React.Element | defaults to: spanThe element to render
disabledboolean | defaults to: falseMakes element non-interactive, even if onClick is provided
refReact.RefProvides access to the React element

You can pass any custom prop as well. This component will forward those props to the rendered element.

When should you use this?

  • You're building a button that looks like plain text.
  • You're building a button that has content spanning multiple columns or rows.
  • You're making a clickable SVG icon.

When shouldn't you use this?

  • You're linking to another page: Use an a tag with an href instead. The anchor tag is semantically correct, allows users to preview the URL, open it in a new tab, and copy the link to their clipboard.
  • You're building a button that looks like a button: This is fairly easy to build as a button element with CSS.