Registry / web-framework / focus-trap-react

focus-trap-react

JSON →
library12.0.0jsnpmunverified

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-react
INSTALL
IMPORT
SIG · FOCUS-TRAP-REACT
F
focus-trap-react
web-frameworkjavascriptv12.0.0
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

FocusTrap
✓ import { FocusTrap } from 'focus-trap-react';
✗ const FocusTrap = require('focus-trap-react').FocusTrap;
Since v11.0.1, the named export `FocusTrap` is preferred. The default export is deprecated and will be removed.
FocusTrap (default export, deprecated)
✓ import FocusTrap from 'focus-trap-react';
✗ const FocusTrap = require('focus-trap-react');
The default export for `FocusTrap` is deprecated since v11.0.1 and will be removed in a future major version. Prefer the named export.
FocusTrapProps (TypeScript types)
✓ import type { FocusTrapProps } from 'focus-trap-react';
Import type definitions explicitly for TypeScript to avoid runtime overhead.

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.

import React, { useState, useRef, useEffect } from 'react'; import { FocusTrap } from 'focus-trap-react'; const Modal = ({ onClose }) => { const trapRef = useRef(null); useEffect(() => { // Optional: Log when the trap is activated/deactivated console.log('Focus trap mounted'); return () => console.log('Focus trap unmounted'); }, []); return ( <FocusTrap active={true} focusTrapOptions={{ onDeactivate: onClose, clickOutsideDeactivates: true, initialFocus: '#close-button', fallbackFocus: '#close-button' }} _ref={trapRef} > <div style={{ position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', backgroundColor: 'white', padding: '20px', border: '1px solid gray', zIndex: 1000 }} aria-modal="true" role="dialog" > <h2>Accessible Modal Dialog</h2> <p>This is content inside the focus trap. You cannot tab outside this box.</p> <input type="text" placeholder="Enter something" /> <button id="close-button" onClick={onClose}>Close Modal</button> <button>Another button</button> </div> </FocusTrap> ); }; const App = () => { const [isModalOpen, setIsModalOpen] = useState(false); return ( <div> <h1>Focus Trap React Demo</h1> <button onClick={() => setIsModalOpen(true)}>Open Modal</button> {isModalOpen && <Modal onClose={() => setIsModalOpen(false)} />} <p>Content behind the modal.</p> <input type="text" placeholder="Outside input" /> </div> ); }; export default App;
Debug
Known issues
breakingThe underlying `focus-trap` dependency was updated to v8.0.0. The `onPostActivate()` callback is now correctly called *after* the initial focus node is focused, rather than before, which was a bug.
fix
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.
affects: >=12.0.0
breakingSupport for `propTypes` and `defaultProps` has been removed. This aligns with React 19's deprecation of these features and forward compatibility with React 18, which already deprecated them.
fix
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`.
affects: >=11.0.0
gotchaThe default export for `FocusTrap` is deprecated. While still available, it is recommended to use the named export for future compatibility.
fix
Change your import statements from `import FocusTrap from 'focus-trap-react';` to `import { FocusTrap } from 'focus-trap-react';`.
affects: >=11.0.1
gotchaThe `FocusTrap` component requires exactly one child element. It cannot be a React Fragment (`<>...</>`) because the component needs a direct reference to a DOM element.
fix
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>`.
affects: >=1.0.0
gotchaThis library only officially supports desktop browsers. While it may function on mobile, it is not officially tested or guaranteed.
fix
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.
affects: >=1.0.0
gotchaInternet Explorer is no longer supported by this library, following Microsoft's discontinuation of support for IE 11.
fix
Do not target Internet Explorer with applications using `focus-trap-react`. Ensure your supported browser matrix does not include IE.
affects: >=1.0.0
Errors
Common errors & fixes
Error: FocusTrap requires a single child element.
You are passing more than one child or a React Fragment to the FocusTrap component.
fix
Wrap your children in a single parent DOM element, like a `<div>`, before passing them to FocusTrap. Example: `<FocusTrap><div>...</div></FocusTrap>`
TypeError: Cannot read properties of undefined (reading 'displayName')
This error can occur in older React versions or specific build configurations when using the named `FocusTrap` export if a default export was expected or vice versa, or if `React.Children.only` fails.
fix
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.
Property 'onPostActivate' does not exist on type 'FocusTrapOptions'.
TypeScript error indicating that the `onPostActivate` option might be used incorrectly or its signature has changed, especially after the v12 update to `focus-trap` v8.
fix
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.
Upgrade
Version history
12.0.0latest on npm
Audit
Dependencies
reactrequiredRequired for React component functionality, minimum version 18.0.0.
react-domrequiredRequired for ReactDOM rendering, minimum version 18.0.0.
@types/reactoptionalTypeScript type definitions for React.
@types/react-domoptionalTypeScript type definitions for ReactDOM.
Agent activity
5 hits · last 30 days
node
4
Resources