Trap focus in a React component

Some actions on a web application requires shifting the focus of an user. We’ll use the focus-trap package to trap focus within a DOM node or React component.

While developing interactive applications for the modern web, changes are that you’ll need to create overlaying elements. When such elements are active, the rest of the page is usually visually hidden and the user is only allowed to interact with this element. We can use ARIA-attributes to help with assistive technologies, but that won’t prevent keyboard users from tabbing out of the active element.

For example, setting `aria-modal=”true”` on an active modal will tell assistive technologies that the elements below the current dialog are not available to interact with ( This, however, will not prevent the user from tabbing out of your modal component. In this case we’ll have to resort to JavaScript and trap the keyboard focus, and keep the tabbed element in our modal overlay.

Trap focus with vanilla JavaScript

Trapping focus and staying accessible is quite complex and fragile functionality ( So we’re going to use the well written focus-trap to help implementing an accessible modal component.

Let’s say that we have the following HTML markup containing the modal.

With a script attached to the HTML page, we can trap the focus when the modal is shown.

The called focus-trap package provides many more options. Like deactivating when clicking outside of the component or trigger deactivating when the ESC key is pressed.

Trap focus with React

To achieve the focus trap with React, we can use the focus-trap-react package. It is a thin wrapper around the original package.

Let’s convert our vanilla JavaScript example to a React component.

You’ll notice that we’ve wrapped the modal with an <FocusTrap /> component. Whenever the trap is active - as indicated by the showModal state - only the children within the trap will get focus.

Closing thoughts

It is quite complex to develop a modal or a dialog component that is accessible to any of your users. Especially when they are visually impaired and depend on the keyboard to navigate through your application. By adding the focus-trap package to your toolbelt, it becomes much easier to create keyboard-navigable components without leaving users behind.

Written by

Technical-minded creative, web entrepreneur and part-time nerd. Eats pixels for breakfast and bytes for lunch. Dinner is a story on its own.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store