01. Leveraging Headless UI
🐇 TL;DR
- We start with a “naive” Modal, which lacks usability and accessibility
- Let’s use Headless UI’s
Dialog
component to supercharge our Modal!
🐢 Background
We’re starting off with a modal component that looks good, but lacks many features in terms of usability and accessibility.
It relies on a isOpen
piece of state, which is used to conditionally show/hide the modal.
There is nothing else to it.
It’s unfortunate, because the modal (or dialog) pattern should ideally support a bunch of features, such as:
- being able to close the modal with the escape key
- manage focus “trapping”
- locking the background page to prevent scrolling
- setting a series of attributes and roles for screen readers
You can learn more about the Dialog/Modal pattern on the ARIA Authoring Practices Guide website.
Headless UI to the rescue
Implementing proper accessibility support is hard, and it’s a lot of work. That’s the reason why “headless” libraries like Headless UI are popular. They take care of all the heavy lifting related to implementing compliant accessibility, including robust keyboard navigation.
Since Headless UI offers a Dialog
component, let’s use this to dramatically improve the usability and accessibility of our Modal component!
🏆 Your first challenge 🏆
In the Gitpod workspace below:
-
Use Headless UI’s
Dialog
component in theModal
component located insrc/components/modal/modal.tsx
. -
Use Headless UI’s
<Dialog.Panel>
and<Dialog.Title>
components to continue the conversion.
Play with the Modal, inspect the markup with the devtools to see what improvements Headless UI brought to our component.
✌️ Good luck!
Open in Gitpod →