focus-trap-react is a React component that wraps the `focus-trap` library, providing an accessible way to trap focus within a DOM element. This is crucial for UI patterns like modals, dialogs, and overlays, ensuring keyboard users cannot tab outside the active component. The current stable version is 12.0.0. The library maintains a steady release cadence, typically releasing new patch versions to update its underlying `focus-trap` dependency, and major versions coinciding with significant updates to `focus-trap` or React compatibility requirements. Its key differentiator is its direct integration with React's component lifecycle, abstracting the imperative `focus-trap` API into declarative props, simplifying its use in React applications for enhanced accessibility.
npm install focus-trap-reactVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to create a basic accessible modal using `FocusTrap`. It shows conditional rendering, custom `focusTrapOptions` for deactivation and initial focus, and proper ARIA attributes.
If you relied on `onPostActivate()` being called before the initial focus, you may need to adjust your logic or use `onActivate()` instead, understanding the new correct timing.
For type validation, use TypeScript. For runtime prop validation, integrate a library like RTV.js, JSON Schema, or yup. Remove any `propTypes` or `defaultProps` definitions from components using `FocusTrap`.
Change your import statements from `import FocusTrap from 'focus-trap-react';` to `import { FocusTrap } from 'focus-trap-react';`.Ensure the `FocusTrap` component wraps a single HTML element or a custom component that renders a single root DOM element. For example, wrap multiple elements in a `<div>`.
Thoroughly test on target mobile devices if using in a mobile-first or responsive application. Be aware that specific mobile browser behaviors might not be accounted for.
Do not target Internet Explorer with applications using `focus-trap-react`. Ensure your supported browser matrix does not include IE.
Wrap your children in a single parent DOM element, like a `<div>`, before passing them to FocusTrap. Example: `<FocusTrap><div>...</div></FocusTrap>`
Ensure you are using `import { FocusTrap } from 'focus-trap-react';` and that your React version is `>=18.0.0`. Also, verify FocusTrap has exactly one child element.Check the `focus-trap` v8 documentation for `onPostActivate` usage. Ensure your `focusTrapOptions` object conforms to the expected type, and review the behavioral change regarding its invocation timing.