Alert

An alert is an element that displays a brief, important message in a way that attracts the user's attention without interrupting the user's task.

It is typically used to inform users about errors in forms or about successful actions.

When displayed, focus should be moved inside it so that screen readers announce the alert's message.

What to put inside the Alert

Check out the ErrorSummary component.

Usage

The Alert component comes with a MessageContainer that can be accessed statically on the Alert component. This MessageContainer component functions as the placeholder for the alerted message. It needs to be in the DOM when the Alert component renders.

// Place the message container where you want the message to be rendered
<Alert.MessageContainer />

// Render the Alert component around the interactive element that triggers the
// alert
<Alert message="Alerted message">
  {({ onOpen, onClose }) => (
    <div>
      <button
        onClick={() => {
          onClose();
        }}
      >
        close
      </button>
      <button
        onClick={() => {
          onOpen();
        }}
      >
        open
      </button>
    </div>
  )}
</Alert>

// Or render the Alert without children to immediately display it once rendered
<Alert message="Alerted message" />

Props

Property nameTypeRequiredValuesDefault
messageReact.ReactNode--
childrenChildFunction--

Here are the complete type definitions:

type ChildFunction = (args: {
  onOpen: () => void,
  onClose: () => void,
}) => React.ReactNode;

Accessibility

Once the onOpen method is called, the alert message is rendered and keyboard focus is moved to the message so that screen readers read it out.

Example

Using the children function

  <Alert.MessageContainer />
  <Alert message="Alerted message">
    {({ onOpen, onClose }) => (
      <div>
        Content
        <button
          onClick={() => {
            onClose();
          }}
        >
          close
        </button>
        <button
          onClick={() => {
            onOpen();
          }}
        >
          open
        </button>
      </div>
    )}
  </Alert>
Content

Without controlling the state

<Alert.MessageContainer />
<Alert message="Alerted message" />