Search code examples
reactjsaccessibility

Best practice to add role="alert" in React conditional rendering


I am coding a notification panel and was warned by my accessibility team that I must add role="alert" for screenreaders.

Roughly my code construction is like this.

export const RootDialog: React.FC = (mode) => {
    return <Dialog footer ={
        <>
            {mode === "normal" && <SomeComponent someprop={mode}>}
            {mode === "success" && <NotificationSuccess someprop={mode}>}
            {mode === "error" && <NotificationError someprop=mode>}
        </>
    }></Dialog>
}

When this Dialog is opened, a Component is added depending on the mode.
What I would like to know, is which is better for screenreaders.

<div role="alert">
    {mode === "normal" && <SomeComponent someprop={mode}>}
    {mode === "success" && <NotificationSuccess someprop={mode}>}
    {mode === "error" && <NotificationError someprop=mode>}
</div>

or

<>
    {mode === "normal" && <div role="alert"><SomeComponent someprop={mode}></div>}
    {mode === "success" && <div role="alert"><NotificationSuccess someprop={mode}></div>}
    {mode === "error" && <div role="alert"><NotificationError someprop=mode></div>}
</>

In the first place, is mode="alert" unnecessary for this RootDialog ?

I found different opinions for this issue on web. If you happen to know reliable article or source code sample, please let me know. Any advice will be appreciated. Thanks in advance.


Solution

  • the accessibility team warned me some screenreader does not read out div with role=alert added after rendering

    Your accessibility team is correct. Dynamically adding a DOM element that has aria-live or a role that has an implicit aria-live is typically not honored by the screen reader. You have to add the new DOM element to an existing live region.

    See my answers in these two questions that talk about adding content to live regions: