---
title: useFocusTrap
description: Trap keyboard focus within a container for accessible modal dialogs.
---
`useFocusTrap()` keeps keyboard focus within a container element while active. This is essential for accessibility - when a modal dialog is open, Tab and Shift+Tab should cycle through focusable elements inside the dialog, not escape to the page behind it.

```tsx
import { useFocusTrap } from '@c15t/nextjs';
import { useRef } from 'react';

function AccessibleModal({ isOpen }: { isOpen: boolean }) {
  const containerRef = useRef<HTMLDivElement>(null);
  useFocusTrap(isOpen, containerRef);

  if (!isOpen) return null;

  return (
    <div ref={containerRef} role="dialog" aria-modal="true">
      <h2>Modal Title</h2>
      <button>Action</button>
      <button>Close</button>
    </div>
  );
}
```

## Parameters

| Parameter      | Type                                     | Description                     |
| -------------- | ---------------------------------------- | ------------------------------- |
| `shouldTrap`   | `boolean`                                | Whether focus should be trapped |
| `containerRef` | `RefObject<HTMLElement \| null> \| null` | Ref to the container element    |

## Behavior

* **Tab**: Moves focus to the next focusable element. Wraps to the first element when reaching the end.
* **Shift+Tab**: Moves focus to the previous focusable element. Wraps to the last element when reaching the start.
* Focus is restored to the previously focused element when the trap is deactivated.

> ℹ️ **Info:**
> ConsentBanner and ConsentDialog use useFocusTrap internally when trapFocus is enabled (default: true). You only need this hook when building custom consent UI.
