Your Div Is Not a Button

Why you should use a real button instead of a div with onClick.

You've probably seen this before. Someone needs something clickable, so they grab a <div>, slap an onClick on it and call it a day. It looks like a button and it works with a mouse.

The problem is that the div is only a button for people using a mouse. Everyone else gets a box of text that does nothing.

TL;DR If it does something when you click it, use a <button>. If it takes you somewhere, use an <a>.

What Your Div Is Missing

A <button> comes with a lot of behavior for free that a div simply doesn't have:

  • It can be focused with the Tab key
  • It can be activated with Enter and Space
  • Screen readers announce it as a button
  • It can be disabled
  • It submits a form when it's inside one

Your div does none of these. Keyboard users can't reach it and screen reader users have no idea it's clickable.

Faking a Button Is a Lot of Work

You can make a div act like a button, but look at what it takes:

<div
role="button"
tabIndex="0"
onClick={save}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault()
save()
}
}}
>
Save
</div>

And that still doesn't handle a disabled state. Compare that to the real thing:

<button onClick={save}>Save</button>

Yep that's it. One line, and it works for everyone.

"But Buttons Are Hard to Style"

This is usually the real reason for the div. Buttons come with browser styles, but they're easy to reset:

.button-reset {
background: none;
border: none;
padding: 0;
font: inherit;
color: inherit;
cursor: pointer;
}

From there you can style it any way you want, just like a div. Leave the focus outline alone though (or replace it with your own), since that's how keyboard users know where they are.

Watch Out for Forms

A button inside a <form> defaults to type="submit". If your button is meant to do something else, like toggling a password field, set the type so it doesn't submit the form:

<button type="button" onClick={togglePassword}>
Show password
</button>

Buttons vs Links

Buttons do things and links go places. If clicking it changes the URL, it should be an <a> with an href so it can be opened in a new tab, bookmarked and shared. If it opens a modal, submits data or toggles something, it's a button.

Have some feedback on this post? .