How to Trap Focus in Next.js and React

Trapped Focus Example
Published on: (Updated on: )
In web development, managing focus is critical for accessibility, especially when creating modal dialogs, pop-ups, or interactive components. Trapping focus ensures that keyboard users can navigate your component without losing focus elsewhere on the page. In this blog post, we'll explore how to implement a simple focus trap using React, specifically in a Next.js environment, with a thorough breakdown of the code.
What is Focus Trapping?
Focus trapping is a technique that restricts keyboard navigation to a specific part of the UI, preventing users from accidentally interacting with elements outside of this section. This is particularly useful in modal dialogs, dropdowns, and other interactive components where users need to focus on specific actions or information.
Setting Up Your Next.js Project
Before we dive into coding, ensure you have a Next.js project set up. If you haven’t created one yet, you can quickly start by running:
npx create-next-app@latest my-focus-trap-app
cd my-focus-trap-appDuring the installation process, answer yes to typescript, tailwind, eslint, and app router.
Once your project is ready, navigate to the directory and create a new component called FocusTrap.tsx.
Implementing the Focus Trap Component
Now, let’s examine the FocusTrap component. This component takes two props: children (the content to be rendered) and active (a boolean to control if the focus trap is active).
Here's the complete focus trap code: