Home > Back-end >  The correct HTML role and the other related attributes for a modal backdrop element (TypeScript Reac
The correct HTML role and the other related attributes for a modal backdrop element (TypeScript Reac

Time:11-28

I'm trying to make a Modal component with React & TypeScript, which has a "click outside to close" functionality; I'm trying to implement that by making a backdrop element: a greyed out HTML div element as a background that has an onClick event that calls the onClose method.

The problem is that when I assign an onClick event on the backdrop element, I get the linting error: Static HTML elements with event handlers require a role.

And when I give it a role of an interactive element, like button for instance, I get these other errors:

  • A control must be associated with a text label.
  • Elements with the 'button' interactive role must be focusable.

So my question is, what is the correct role to give to the backdrop element, and what should the other related attributes be?

P.S. I'm not interested in disabling the linting rule.

CodePudding user response:

I think your problem originates with accessibility. Screen readers and such need info to identify clickable elements.

To bypass this, you can set it to be aria-hidden.

Compare: https://stackoverflow.com/a/64022904/17519505

and https://github.com/mui-org/material-ui/blob/42ce3598db2c19956d9cd852b43d0c96f61f697b/packages/mui-base/src/BackdropUnstyled/BackdropUnstyled.js#L18

(lines 23 (using a div), 44 (aria-hidden) and 52 (onClick slips in here)

CodePudding user response:

According to w3 specifications, the role presentation seems adequate for a backdrop (something purely presentational): https://www.w3.org/TR/wai-aria-1.1/#presentation

Adding the role presentation should resolve the lint error without any additional modification required.

However, I recommend exploring a different approach for the "click outside" functionality. There is a way of observing for actual click out of the modal by adding a click listener to the document and checking if the click target is not contained in your modal. This answer has a reasonable solution: Detect click outside React component.

That way you can avoid adding interactivity to an element that's supposed to be purely presentational. The a11y linter and tools will be happier.

  • Related