Ariakit
/

Checkbox as button

Rendering a custom Checkbox as a button element in React, while keeping it accessible to screen reader and keyboard users.

import { Checkbox, useCheckboxStore } from "@ariakit/react";
import "./style.css";
export default function Example() {
const checkbox = useCheckboxStore();
const label = checkbox.useState((state) =>
state.value ? "Checked" : "Unchecked",
);
return (
<Checkbox store={checkbox} className="button" render={<button />}>
{label}
);
}

Components

Activating on Enter

By default, native checkbox elements are activated on Space, but not on Enter. The Ariakit Checkbox component allows you to control this behavior using the clickOnEnter and clickOnSpace props. However, when rendering the Checkbox as any non-native input element, the clickOnEnter prop will be automatically set to true.

Reading the state

In this example, we're reading the value state from the checkbox store to render the button's text. This is done by using the selector form of the useState hook:

const label = checkbox.useState((state) =>
state.value ? "Checked" : "Unchecked"
);

Learn more about reading the state on the Component stores guide.

Styling

When rendering the Checkbox component as a non-native input element, the :checked pseudo-class is not supported. To style the checked state, use the aria-checked attribute selector:

.button[aria-checked="true"] {
background-color: hsl(204 100% 40%);
color: hsl(204 20% 100%);
}

Learn more on the Styling guide.

Stay tuned

Join 1,000+ subscribers and receive monthly tips & updates on new Ariakit content.

No spam. Unsubscribe anytime. Read latest issue