Skip to content

Alert

Screen-reader-friendly alert messages. In many apps developers add "alert" messages when network events or other things happen. Users with assistive technologies may not know about the message unless you develop for it.

The Alert component will announce to assistive technologies whatever you render to the screen. If you don't have a screen reader on you won't notice a difference between rendering <Alert> vs. a <div>.

function Example(props) {  const [messages, setMessages] = React.useState([]);  return (    <div>      <button        onClick={() => {          setMessages((prevMessages) =>            prevMessages.concat([`Message #${prevMessages.length + 1}`])          );          setTimeout(() => {            setMessages((prevMessages) => prevMessages.slice(1));          }, 5000);        }}      >        Add a message      </button>      <div>        {messages.map((message, index) => (          <Alert key={index}>{message}</Alert>        ))}      </div>    </div>  );}

Installation

From the command line in your project directory, run npm install @reach/alert or yarn add @reach/alert. Then import the component:

npm install @reach/alert# oryarn add @reach/alert
import Alert from "@reach/alert";

Component API

Alert

Alert Props

PropTypeRequired
div props
typeenumfalse
childrennodetrue`
Alert div props

Any props not listed above will be spread onto the underlying div element.

function Example() {  return (    <Alert      style={{        background: "hsla(10, 50%, 50%, .10)",        padding: "10px",      }}    >      ❗️ Woah! Something went wrong.    </Alert>  );}
Alert type

type?: "assertive" | "polite"

Controls whether the assistive technology should read immediately ("assertive") or wait until the user is idle ("polite").

<Alert type="polite">  This is the default</Alert>
<Alert type="assertive">  If a screen reader is currently reading something and  you render this, it will interrupt the user and read  this immediately.</Alert>

You should probably stick with polite most of the time.

Alert children

children: React.ReactNode;

Regular React children.

<Alert>  <p>Whatever you want here</p>  <p>Is fine.</p></Alert>