Skip to main content

Live Region

BetaSince 0.1.0

Announces a message to screen readers, such as Copied or a form error, with announce().

import { LiveRegion, announce } from "@anantya/uix";

Overview

announce() tells screen reader users about a change they can't see from where they are, such as "Reminder sent" after an action, or a form error. It writes to a LiveRegion, which ThemeProvider renders for the whole app, so you only call announce().

Mount a LiveRegion yourself only in an app without ThemeProvider.

Signature

function announce(message: string, politeness?: Politeness): void;

function LiveRegion(): ReactElement;

type Politeness = "polite" | "assertive";

Parameters

ParameterTypeDefaultDescription
messagestring-What a screen reader reads, such as "Reminder sent to Mehta Textiles".
politeness"polite" | "assertive""polite"polite waits until the screen reader finishes what it is reading; assertive interrupts it.

LiveRegion takes no props.

Returns

announce() returns nothing. The message is read about 100 ms after the call, and cleared 7 seconds later.

LiveRegion renders two visually hidden regions: a polite role="status" and an assertive role="alert". It renders on the server, so the regions exist before the first message.

Example

Send reminder shows that it is sending, then announces "Reminder sent to Mehta Textiles" and shows when it was sent.

No reminder sent yet

Code
"use client";

import { announce, Button } from "@anantya/uix";
import { useState } from "react";

const sendReminder = () => new Promise((resolve) => setTimeout(resolve, 1000));

export default function SendReminder() {
const [sending, setSending] = useState(false);
const [sent, setSent] = useState(false);

return (
<div className="flex flex-col items-center gap-2 text-sm">
<Button
loading={sending}
loadingText="Sending…"
onClick={async () => {
setSending(true);
await sendReminder();
setSending(false);
setSent(true);
announce("Reminder sent to Mehta Textiles");
}}
>
Send reminder
</Button>
<p className="text-muted-foreground">
{sent ? "Last reminder sent just now" : "No reminder sent yet"}
</p>
</div>
);
}

Notes

  • Keep messages short, and announce assertively only for errors that need action now
  • Don't announce what a screen reader reads already, such as the label of the element that gets focus
  • The same message twice in a row is read twice, and a newer message replaces one not read yet
  • On the server, and when no LiveRegion is mounted, announce() does nothing
  • The LiveRegion mounted last takes over until it unmounts. An open Dialog renders its own, so messages are heard while the rest of the page is inert

Changelog

Every change to Live Region since 0.1.0 is in the release notes.

© Anantya TechLabs. All rights reserved.