And the WAI site, or the APG site, has a pattern for that. It's called the Disclosure So Hide pattern. It's documented. And you have to have these three primary keyboard interactions to solve that criteria. You have to support, say, space bar and enter key presses, escape key presses, mouse clicks.
And to do that in React, you start with JSX button element, which, under the hood, renders an HTML button element, which, by default, supports mouse clicks, enter key presses, and space bar key presses for free. Magic. Awesome. So, once you have that, that's when you add just enough ARIA support to let screen readers know when that widget is going to be opened and closed. And in the case of if you have many widgets on the page, which container on that page is being opened and closed?
So on our button, we are going to add the ARIA controls attribute to tell assistive technology which element the button is controlling. In this case, it is the container's ID. And then we are going to add ARIA expanded to tell whether the widget is expanded or not. It's Boolean. And ARIA label in cases where we need a more accurate button label, especially if we are doing icon buttons. And then we are going to add state and click handlers to toggle the container open and closed. So when we do that, we are going to use the use date hook. And define set as open and initialize use date to false. And optionally, we are going to set a default expanded prop to use date for those cases when we have to have our widget open by default. For example, if you are working at a bank and you have to have a terms of service, widget open by default. That is something that banks have to do. So it is nice to have that prop in your component.
Then, when you have that state defined, you can pop it into a toggle open function and toggle that set is open to false with that toggle open function. Pop that function into your on click handler. And then in your buttons re-expanded prop, the re-expanded prop will communicate whether it is open to a false depending on that is open prop. Then, in your div, you can pop that is open prop with the children and only render the children if that is open prop is true. Now you have the basics of disclosure widget. Then you can add a little bit of enhancements, like if you want to take it a little bit further with UX, like focus management. And this is like the advance. The enhanced pattern for disclosure widgets. For example, when you use the escape key, when you close the widget with the escape key, it will return focus right back to that button.
Comments