I have a website with modals that work via React Portals and they work great, powered by a popular library. However, in one place, due to various sensible reasons, we have a custom modal that isn't inside a portal and isn't powered by the library.
For accessibility, I've tried to set the modal itself to role="modal" and aria-modal="true" in order to hint to screen readers that they should ignore the background. However, the background isn't ignored. This site mentions that sometimes you do need aria-hidden on the background. When checking how React Portal and the library does it, it adds an aria-hidden attribute to the body. So I figured I would give this a go.
However, when I create a useEffect to do that and call document.body.setAttribute('aria-hidden', 'true')
, it just ignores me. I know the code works, I can set other attributes, but not this one. Do any of you know why that's happening?
Edit: Regarding a clarification for why I'm trying to do this, this is the HTML tree from react-modal
, the library we use that I mentioned above, with 1.7m weekly downloads:
I'd love to understand why they're doing that, especially when the modal is a child of the body that is being hidden. As one of the comments points out, that's against the Aria guidelines, seem like it shouldn't work, is weird but does actually work.
When I try this in a snippet:
function ariaHideBody() {
console.log('hiding body!!!')
document.body.setAttribute('aria-hidden', 'true');
}
<h1>
Example for <a href="https://stackoverflow.com/questions/79437209/document-body-setattributearia-hidden-true-is-ignored">SO Post about programmatically setting aria-hidden on the document body</a>
</h1>
<button onclick="ariaHideBody()">
Click me to make the body aria hidden
</button>
...I get the following Error in the Chrome console:
Blocked aria-hidden on a <body> element because it would hide the entire accessibility tree from assistive technology users. For more details, see the aria-hidden section of the WAI-ARIA specification at https://w3c.github.io/aria/#aria-hidden.
That said, I then actually do subsequently see that the aria-hidden="true"
attribute has been added to the body, so something curious might be going on there, perhaps related to the <body/>
being in an <iframe/>
.
Regardless, the warning is absolutely correct— the modal you are throwing up on the page is contained within the document <body/>
element, so putting aria-hidden="true"
on the <body/>
will hide all it's content including your modal. So this is, obviously, not a recommended approach.
You're correct to be leveraging the ARIA Authoring Practices Guide Patterns page and seeing how they recommend authoring a modal; as the one's that wrote the spec, they'll likely have the best, most idiomatic and well-supported approach. However, I'll note that the section you are referring to in which they state "sometimes you do need aria-hidden on the background" has some important caveats:
aria-hidden
set to true
."