beta

Button

A button allows a user to perform an action, with mouse, touch, and keyboard interactions.

installyarn add react-aria-components
version1.0.0-beta.1
usageimport {Button} from 'react-aria-components'

Example#


import {Button} from 'react-aria-components';

<Button onPress={() => alert('Hello world!')}>Press me</Button>
import {Button} from 'react-aria-components';

<Button onPress={() => alert('Hello world!')}>
  Press me
</Button>
import {Button} from 'react-aria-components';

<Button
  onPress={() =>
    alert(
      'Hello world!'
    )}
>
  Press me
</Button>
Show CSS
.react-aria-Button {
  --border-color: var(--spectrum-alias-border-color);
  --border-color-pressed: var(--spectrum-alias-border-color-down);
  --border-color-disabled: var(--spectrum-alias-border-color-disabled);
  --background-color: var(--spectrum-global-color-gray-50);
  --background-color-pressed: var(--spectrum-global-color-gray-100);
  --text-color: var(--spectrum-alias-text-color);
  --text-color-disabled: var(--spectrum-alias-text-color-disabled);
  --focus-ring-color: slateblue;

  color: var(--text-color);
  background: var(--background-color);
  border: 1px solid var(--border-color);
  border-radius: 4px;
  appearance: none;
  vertical-align: middle;
  font-size: 1rem;
  text-align: center;
  margin: 0;
  outline: none;
  padding: 6px 10px;
  text-decoration: none;

  &[data-pressed] {
    box-shadow: inset 0 1px 2px rgb(0 0 0 / 0.1);
    background: var(--background-color-pressed);
    border-color: var(--border-color-pressed);
  }

  &[data-focus-visible] {
    border-color: var(--focus-ring-color);
    box-shadow: 0 0 0 1px var(--focus-ring-color);
  }

  &[data-disabled]{
    border-color: var(--border-color-disabled);
    color: var(--text-color-disabled);
  }
}

@media (forced-colors: active) {
  .react-aria-Button {
    forced-color-adjust: none;
    --border-color: ButtonBorder;
    --border-color-pressed: ButtonBorder;
    --border-color-disabled: GrayText;
    --background-color: ButtonFace;
    --background-color-pressed: ButtonFace;
    --text-color: ButtonText;
    --text-color-disabled: GrayText;
    --focus-ring-color: Highlight;
  }
}
.react-aria-Button {
  --border-color: var(--spectrum-alias-border-color);
  --border-color-pressed: var(--spectrum-alias-border-color-down);
  --border-color-disabled: var(--spectrum-alias-border-color-disabled);
  --background-color: var(--spectrum-global-color-gray-50);
  --background-color-pressed: var(--spectrum-global-color-gray-100);
  --text-color: var(--spectrum-alias-text-color);
  --text-color-disabled: var(--spectrum-alias-text-color-disabled);
  --focus-ring-color: slateblue;

  color: var(--text-color);
  background: var(--background-color);
  border: 1px solid var(--border-color);
  border-radius: 4px;
  appearance: none;
  vertical-align: middle;
  font-size: 1rem;
  text-align: center;
  margin: 0;
  outline: none;
  padding: 6px 10px;
  text-decoration: none;

  &[data-pressed] {
    box-shadow: inset 0 1px 2px rgb(0 0 0 / 0.1);
    background: var(--background-color-pressed);
    border-color: var(--border-color-pressed);
  }

  &[data-focus-visible] {
    border-color: var(--focus-ring-color);
    box-shadow: 0 0 0 1px var(--focus-ring-color);
  }

  &[data-disabled]{
    border-color: var(--border-color-disabled);
    color: var(--text-color-disabled);
  }
}

@media (forced-colors: active) {
  .react-aria-Button {
    forced-color-adjust: none;
    --border-color: ButtonBorder;
    --border-color-pressed: ButtonBorder;
    --border-color-disabled: GrayText;
    --background-color: ButtonFace;
    --background-color-pressed: ButtonFace;
    --text-color: ButtonText;
    --text-color-disabled: GrayText;
    --focus-ring-color: Highlight;
  }
}
.react-aria-Button {
  --border-color: var(--spectrum-alias-border-color);
  --border-color-pressed: var(--spectrum-alias-border-color-down);
  --border-color-disabled: var(--spectrum-alias-border-color-disabled);
  --background-color: var(--spectrum-global-color-gray-50);
  --background-color-pressed: var(--spectrum-global-color-gray-100);
  --text-color: var(--spectrum-alias-text-color);
  --text-color-disabled: var(--spectrum-alias-text-color-disabled);
  --focus-ring-color: slateblue;

  color: var(--text-color);
  background: var(--background-color);
  border: 1px solid var(--border-color);
  border-radius: 4px;
  appearance: none;
  vertical-align: middle;
  font-size: 1rem;
  text-align: center;
  margin: 0;
  outline: none;
  padding: 6px 10px;
  text-decoration: none;

  &[data-pressed] {
    box-shadow: inset 0 1px 2px rgb(0 0 0 / 0.1);
    background: var(--background-color-pressed);
    border-color: var(--border-color-pressed);
  }

  &[data-focus-visible] {
    border-color: var(--focus-ring-color);
    box-shadow: 0 0 0 1px var(--focus-ring-color);
  }

  &[data-disabled]{
    border-color: var(--border-color-disabled);
    color: var(--text-color-disabled);
  }
}

@media (forced-colors: active) {
  .react-aria-Button {
    forced-color-adjust: none;
    --border-color: ButtonBorder;
    --border-color-pressed: ButtonBorder;
    --border-color-disabled: GrayText;
    --background-color: ButtonFace;
    --background-color-pressed: ButtonFace;
    --text-color: ButtonText;
    --text-color-disabled: GrayText;
    --focus-ring-color: Highlight;
  }
}

Features#


On the surface, building a custom styled button seems simple. However, there are many cross browser inconsistencies in interactions and accessibility features to consider. Button handles all of these interactions for you, so you can focus on the styling.

  • Styleable – Hover, press, and keyboard focus states are provided for easy styling. These states only apply when interacting with an appropriate input device, unlike CSS pseudo classes.
  • Accessible – Uses a native <button> element under the hood, with support for the Space and Enter keys.
  • Cross-browser – Mouse, touch, keyboard, and focus interactions are normalized to ensure consistency across browsers and devices.

Read our blog post about the complexities of building buttons that work well across devices and interaction methods to learn more.

Anatomy#


Buttons consist of a clickable area usually containing a textual label or an icon that users can click to perform an action. In addition, keyboard users may activate buttons using the Space or Enter keys.

If a visual label is not provided (e.g. an icon only button), then an aria-label or aria-labelledby prop must be passed to identify the button to assistive technology.

Events#


Button supports user interactions via mouse, keyboard, and touch. You can handle all of these via the onPress prop. This is similar to the standard onClick event, but normalized to support all interaction methods equally. In addition, the onPressStart, onPressEnd, and onPressChange events are fired as the user interacts with the button.

Each of these handlers receives a PressEvent, which exposes information about the target and the type of event that triggered the interaction. See usePress for more details.

function Example() {
  let [pointerType, setPointerType] = React.useState('');

  return (
    <>
      <Button
        onPressStart={(e) => setPointerType(e.pointerType)}
        onPressEnd={() => setPointerType('')}
      >
        Press me
      </Button>
      <p>
        {pointerType
          ? `You are pressing the button with a ${pointerType}!`
          : 'Ready to be pressed.'}
      </p>
    </>
  );
}
function Example() {
  let [pointerType, setPointerType] = React.useState('');

  return (
    <>
      <Button
        onPressStart={(e) => setPointerType(e.pointerType)}
        onPressEnd={() => setPointerType('')}
      >
        Press me
      </Button>
      <p>
        {pointerType
          ? `You are pressing the button with a ${pointerType}!`
          : 'Ready to be pressed.'}
      </p>
    </>
  );
}
function Example() {
  let [
    pointerType,
    setPointerType
  ] = React.useState('');

  return (
    <>
      <Button
        onPressStart={(e) =>
          setPointerType(
            e.pointerType
          )}
        onPressEnd={() =>
          setPointerType(
            ''
          )}
      >
        Press me
      </Button>
      <p>
        {pointerType
          ? `You are pressing the button with a ${pointerType}!`
          : 'Ready to be pressed.'}
      </p>
    </>
  );
}

Disabled#


A Button can be disabled using the isDisabled prop.

<Button isDisabled>Pin</Button>
<Button isDisabled>Pin</Button>
<Button isDisabled>
  Pin
</Button>

The Button component always represents a button semantically. To create a link that visually looks like a button, use the Link component instead. You can reuse the same styles you apply to the Button component on the Link.

import {Link} from 'react-aria-components';

<Link className="react-aria-Button" href="https://adobe.com/" target="_blank">
  Adobe
</Link>
import {Link} from 'react-aria-components';

<Link
  className="react-aria-Button"
  href="https://adobe.com/"
  target="_blank"
>
  Adobe
</Link>
import {Link} from 'react-aria-components';

<Link
  className="react-aria-Button"
  href="https://adobe.com/"
  target="_blank"
>
  Adobe
</Link>

Props#


NameTypeDefaultDescription
formstring

The

element to associate the button with. The value of this attribute must be the id of a
in the same document.

formActionstring

The URL that processes the information submitted by the button. Overrides the action attribute of the button's form owner.

formEncTypestringIndicates how to encode the form data that is submitted.
formMethodstringIndicates the HTTP method used to submit the form.
formNoValidatebooleanIndicates that the form is not to be validated when it is submitted.
formTargetstringOverrides the target attribute of the button's form owner.
namestringSubmitted as a pair with the button's value as part of the form data.
valuestringThe value associated with the button's name when it's submitted with the form data.
isDisabledbooleanWhether the button is disabled.
autoFocusbooleanWhether the element should receive focus on render.
type'button''submit''reset''button'The behavior of the button when used in an HTML form.
childrenReactNode( (values: ButtonRenderProps )) => ReactNodeThe children of the component. A function may be provided to alter the children based on component state.
classNamestring( (values: ButtonRenderProps )) => stringThe CSS className for the element. A function may be provided to compute the class based on component state.
styleCSSProperties( (values: ButtonRenderProps )) => CSSPropertiesThe inline style for the element. A function may be provided to compute the style based on component state.
Events
NameTypeDescription
onPress( (e: PressEvent )) => voidHandler that is called when the press is released over the target.
onPressStart( (e: PressEvent )) => voidHandler that is called when a press interaction starts.
onPressEnd( (e: PressEvent )) => void

Handler that is called when a press interaction ends, either over the target or when the pointer leaves the target.

onPressChange( (isPressed: boolean )) => voidHandler that is called when the press state changes.
onPressUp( (e: PressEvent )) => void

Handler that is called when a press is released over the target, regardless of whether it started on the target or not.

onFocus( (e: FocusEvent<Target> )) => voidHandler that is called when the element receives focus.
onBlur( (e: FocusEvent<Target> )) => voidHandler that is called when the element loses focus.
onFocusChange( (isFocused: boolean )) => voidHandler that is called when the element's focus status changes.
onKeyDown( (e: KeyboardEvent )) => voidHandler that is called when a key is pressed.
onKeyUp( (e: KeyboardEvent )) => voidHandler that is called when a key is released.
Layout
NameTypeDescription
slotstringnull

A slot name for the component. Slots allow the component to receive props from a parent component. An explicit null value indicates that the local props completely override all props received from a parent.

Accessibility
NameTypeDescription
idstringThe element's unique identifier. See MDN.
excludeFromTabOrderboolean

Whether to exclude the element from the sequential tab order. If true, the element will not be focusable via the keyboard by tabbing. This should be avoided except in rare scenarios where an alternative means of accessing the element or its functionality via the keyboard is available.

aria-expandedboolean'true''false'Indicates whether the element, or another grouping element it controls, is currently expanded or collapsed.
aria-haspopupboolean'menu''listbox''tree''grid''dialog''true''false'Indicates the availability and type of interactive popup element, such as menu or dialog, that can be triggered by an element.
aria-controlsstringIdentifies the element (or elements) whose contents or presence are controlled by the current element.
aria-pressedboolean'true''false''mixed'Indicates the current "pressed" state of toggle buttons.
aria-labelstringDefines a string value that labels the current element.
aria-labelledbystringIdentifies the element (or elements) that labels the current element.
aria-describedbystringIdentifies the element (or elements) that describes the object.
aria-detailsstringIdentifies the element (or elements) that provide a detailed, extended description for the object.

Styling#


React Aria components can be styled in many ways, including using CSS classes, inline styles, utility classes (e.g. Tailwind), CSS-in-JS (e.g. Styled Components), etc. By default, all components include a builtin className attribute which can be targeted using CSS selectors. These follow the react-aria-ComponentName naming convention.

.react-aria-Button {
  /* ... */
}
.react-aria-Button {
  /* ... */
}
.react-aria-Button {
  /* ... */
}

A custom className can also be specified on any component. This overrides the default className provided by React Aria with your own.

<Button className="my-button">
  {/* ... */}
</Button>
<Button className="my-button">
  {/* ... */}
</Button>
<Button className="my-button">
  {/* ... */}
</Button>

In addition, some components support multiple UI states (e.g. focused, placeholder, readonly, etc.). React Aria components expose states using data attributes, which you can target in CSS selectors. For example:

.react-aria-Button[data-pressed] {
  /* ... */
}
.react-aria-Button[data-pressed] {
  /* ... */
}
.react-aria-Button[data-pressed] {
  /* ... */
}

The className and style props also accept functions which receive states for styling. This lets you dynamically determine the classes or styles to apply, which is useful when using utility CSS libraries like Tailwind.

<Button
  className={({ isPressed }) => isPressed ? 'bg-gray-700' : 'bg-gray-600'}
/>
<Button
  className={({ isPressed }) =>
    isPressed ? 'bg-gray-700' : 'bg-gray-600'}
/>
<Button
  className={(
    { isPressed }
  ) =>
    isPressed
      ? 'bg-gray-700'
      : 'bg-gray-600'}
/>

Render props may also be used as children to alter what elements are rendered based on the current state. For example, you could render an extra element when the button is in a pressed state.

<Button>
  {({isPressed}) => (
    <>
      {isPressed && <PressHighlight />}
      Press me
    </>
  )}
</Button>
<Button>
  {({isPressed}) => (
    <>
      {isPressed && <PressHighlight />}
      Press me
    </>
  )}
</Button>
<Button>
  {({ isPressed }) => (
    <>
      {isPressed && (
        <PressHighlight />
      )}
      Press me
    </>
  )}
</Button>

The states, selectors, and render props for Button are documented below.

NameCSS SelectorDescription
isHovered[data-hovered]Whether the button is currently hovered with a mouse.
isPressed[data-pressed]Whether the button is currently in a pressed state.
isFocused[data-focused]Whether the button is focused, either via a mouse or keyboard.
isFocusVisible[data-focus-visible]Whether the button is keyboard focused.
isDisabled[data-disabled]Whether the button is disabled.

Advanced customization#


Contexts#

All React Aria Components export a corresponding context that can be used to send props to them from a parent element. This enables you to build your own compositional APIs similar to those found in React Aria Components itself. You can send any prop or ref via context that you could pass to the corresponding component. The local props and ref on the component are merged with the ones passed via context, with the local props taking precedence (following the rules documented in mergeProps).

ComponentContextPropsRef
ButtonButtonContextButtonPropsHTMLButtonElement

This example shows a ButtonGroup component that renders a group of buttons. The entire group can be marked as disabled via the isDisabled prop, which is passed to all child buttons via the ButtonContext provider.

import {ButtonContext} from 'react-aria-components';

interface ButtonGroupProps {
  children?: React.ReactNode,
  isDisabled?: boolean
}

function ButtonGroup({children, isDisabled}: ButtonGroupProps) {
  return (
    <div style={{display: 'flex', gap: 8}}>
      <ButtonContext.Provider value={{isDisabled}}>        {children}
      </ButtonContext.Provider>
    </div>
  );
}

<ButtonGroup isDisabled>
  <Button>Save</Button>
  <Button>Publish</Button>
</ButtonGroup>
import {ButtonContext} from 'react-aria-components';

interface ButtonGroupProps {
  children?: React.ReactNode;
  isDisabled?: boolean;
}

function ButtonGroup(
  { children, isDisabled }: ButtonGroupProps
) {
  return (
    <div style={{ display: 'flex', gap: 8 }}>
      <ButtonContext.Provider value={{ isDisabled }}>        {children}
      </ButtonContext.Provider>
    </div>
  );
}

<ButtonGroup isDisabled>
  <Button>Save</Button>
  <Button>Publish</Button>
</ButtonGroup>
import {ButtonContext} from 'react-aria-components';

interface ButtonGroupProps {
  children?:
    React.ReactNode;
  isDisabled?: boolean;
}

function ButtonGroup(
  {
    children,
    isDisabled
  }: ButtonGroupProps
) {
  return (
    <div
      style={{
        display: 'flex',
        gap: 8
      }}
    >
      <ButtonContext.Provider
        value={{
          isDisabled
        }}
      >        {children}
      </ButtonContext.Provider>
    </div>
  );
}

<ButtonGroup
  isDisabled
>
  <Button>Save</Button>
  <Button>
    Publish
  </Button>
</ButtonGroup>

Hooks#

If you need to customize things further, such as intercepting events or customizing DOM elements, you can drop down to the lower level Hook-based API. Consume from ButtonContext in your component with useContextProps to make it compatible with other React Aria Components. See useButton for more details.

This example uses Framer Motion to create an AnimatedButton component that animates based on the isPressed state provided by useButton. It can be used standalone or as a part of any React Aria component.

import type {ButtonProps} from 'react-aria-components';
import {ButtonContext, useContextProps} from 'react-aria-components';
import {useButton} from 'react-aria';
import {motion} from 'framer-motion';

const AnimatedButton = React.forwardRef(
  (props: ButtonProps, ref: React.ForwardedRef<HTMLButtonElement>) => {
    // Merge the local props and ref with the ones provided via context.
    [props, ref] = useContextProps(props, ref, ButtonContext);
    let { buttonProps, isPressed } = useButton(props, ref);
    return (
      <motion.button
        {...buttonProps}
        ref={ref}
        animate={{
          scale: isPressed ? 0.9 : 1
        }}
      >
        {props.children}
      </motion.button>
    );
  }
);
import type {ButtonProps} from 'react-aria-components';
import {
  ButtonContext,
  useContextProps
} from 'react-aria-components';
import {useButton} from 'react-aria';
import {motion} from 'framer-motion';

const AnimatedButton = React.forwardRef(
  (
    props: ButtonProps,
    ref: React.ForwardedRef<HTMLButtonElement>
  ) => {
    // Merge the local props and ref with the ones provided via context.
    [props, ref] = useContextProps(
      props,
      ref,
      ButtonContext
    );
    let { buttonProps, isPressed } = useButton(props, ref);
    return (
      <motion.button
        {...buttonProps}
        ref={ref}
        animate={{
          scale: isPressed ? 0.9 : 1
        }}
      >
        {props.children}
      </motion.button>
    );
  }
);
import type {ButtonProps} from 'react-aria-components';
import {
  ButtonContext,
  useContextProps
} from 'react-aria-components';
import {useButton} from 'react-aria';
import {motion} from 'framer-motion';

const AnimatedButton =
  React.forwardRef(
    (
      props: ButtonProps,
      ref:
        React.ForwardedRef<
          HTMLButtonElement
        >
    ) => {
      // Merge the local props and ref with the ones provided via context.
      [props, ref] =
        useContextProps(
          props,
          ref,
          ButtonContext
        );
      let {
        buttonProps,
        isPressed
      } = useButton(
        props,
        ref
      );
      return (
        <motion.button
          {...buttonProps}
          ref={ref}
          animate={{
            scale:
              isPressed
                ? 0.9
                : 1
          }}
        >
          {props
            .children}
        </motion.button>
      );
    }
  );