How to create an accessible React modal

A step-by-step guide to creating an accessible and reusable modal component in React

This article is originally published on Tinloof.

A modal dialog is a window overlaid on top of the main application. It’s an inert window where the user can’t interact with the rest of the application.

Creating a modal in React is fairly easy. There are dozens of resources that explain how to do so, including the React documentation. This article provides an in-depth step-by-step guide to building a modal component that is accessible and reusable. We will follow the official W3C requirements for building an accessible modal dialog with a reusable API.

Let’s approach our task with a few iterations and try to meet the following requirements:

A reusable component API: we should be able to easily use our accessible modal anywhere and populate it with content.

we should be able to easily use our accessible modal anywhere and populate it with content. Accessible markup.

We should be able to open & close the modal just using the keyboard.

Trap the focus in the modal: since the modal is an inert component, the keyboard navigation should be trapped inside of it once it’s open.

Initial setup: a simple demo container