{"id":10909,"library":"focus-trap-react","title":"React Focus Trap Component","description":"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.","status":"active","version":"12.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/focus-trap/focus-trap-react","tags":["javascript","react","reactjs","react-component","aria","accessibility","modal","dialog","focus","typescript"],"install":[{"cmd":"npm install focus-trap-react","lang":"bash","label":"npm"},{"cmd":"yarn add focus-trap-react","lang":"bash","label":"yarn"},{"cmd":"pnpm add focus-trap-react","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for React component functionality, minimum version 18.0.0.","package":"react","optional":false},{"reason":"Required for ReactDOM rendering, minimum version 18.0.0.","package":"react-dom","optional":false},{"reason":"TypeScript type definitions for React.","package":"@types/react","optional":true},{"reason":"TypeScript type definitions for ReactDOM.","package":"@types/react-dom","optional":true}],"imports":[{"note":"Since v11.0.1, the named export `FocusTrap` is preferred. The default export is deprecated and will be removed.","wrong":"const FocusTrap = require('focus-trap-react').FocusTrap;","symbol":"FocusTrap","correct":"import { FocusTrap } from 'focus-trap-react';"},{"note":"The default export for `FocusTrap` is deprecated since v11.0.1 and will be removed in a future major version. Prefer the named export.","wrong":"const FocusTrap = require('focus-trap-react');","symbol":"FocusTrap (default export, deprecated)","correct":"import FocusTrap from 'focus-trap-react';"},{"note":"Import type definitions explicitly for TypeScript to avoid runtime overhead.","symbol":"FocusTrapProps (TypeScript types)","correct":"import type { FocusTrapProps } from 'focus-trap-react';"}],"quickstart":{"code":"import React, { useState, useRef, useEffect } from 'react';\nimport { FocusTrap } from 'focus-trap-react';\n\nconst Modal = ({ onClose }) => {\n  const trapRef = useRef(null);\n\n  useEffect(() => {\n    // Optional: Log when the trap is activated/deactivated\n    console.log('Focus trap mounted');\n    return () => console.log('Focus trap unmounted');\n  }, []);\n\n  return (\n    <FocusTrap\n      active={true}\n      focusTrapOptions={{\n        onDeactivate: onClose,\n        clickOutsideDeactivates: true,\n        initialFocus: '#close-button',\n        fallbackFocus: '#close-button'\n      }}\n      _ref={trapRef}\n    >\n      <div\n        style={{\n          position: 'fixed',\n          top: '50%',\n          left: '50%',\n          transform: 'translate(-50%, -50%)',\n          backgroundColor: 'white',\n          padding: '20px',\n          border: '1px solid gray',\n          zIndex: 1000\n        }}\n        aria-modal=\"true\"\n        role=\"dialog\"\n      >\n        <h2>Accessible Modal Dialog</h2>\n        <p>This is content inside the focus trap. You cannot tab outside this box.</p>\n        <input type=\"text\" placeholder=\"Enter something\" />\n        <button id=\"close-button\" onClick={onClose}>Close Modal</button>\n        <button>Another button</button>\n      </div>\n    </FocusTrap>\n  );\n};\n\nconst App = () => {\n  const [isModalOpen, setIsModalOpen] = useState(false);\n\n  return (\n    <div>\n      <h1>Focus Trap React Demo</h1>\n      <button onClick={() => setIsModalOpen(true)}>Open Modal</button>\n      {isModalOpen && <Modal onClose={() => setIsModalOpen(false)} />}\n      <p>Content behind the modal.</p>\n      <input type=\"text\" placeholder=\"Outside input\" />\n    </div>\n  );\n};\n\nexport default App;\n","lang":"typescript","description":"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."},"warnings":[{"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.","message":"The 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.","severity":"breaking","affected_versions":">=12.0.0"},{"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`.","message":"Support 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.","severity":"breaking","affected_versions":">=11.0.0"},{"fix":"Change your import statements from `import FocusTrap from 'focus-trap-react';` to `import { FocusTrap } from 'focus-trap-react';`.","message":"The default export for `FocusTrap` is deprecated. While still available, it is recommended to use the named export for future compatibility.","severity":"gotcha","affected_versions":">=11.0.1"},{"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>`.","message":"The `FocusTrap` component requires exactly one child element. It cannot be a React Fragment (`<>...</>`) because the component needs a direct reference to a DOM element.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"This library only officially supports desktop browsers. While it may function on mobile, it is not officially tested or guaranteed.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Do not target Internet Explorer with applications using `focus-trap-react`. Ensure your supported browser matrix does not include IE.","message":"Internet Explorer is no longer supported by this library, following Microsoft's discontinuation of support for IE 11.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Wrap your children in a single parent DOM element, like a `<div>`, before passing them to FocusTrap. Example: `<FocusTrap><div>...</div></FocusTrap>`","cause":"You are passing more than one child or a React Fragment to the FocusTrap component.","error":"Error: FocusTrap requires a single child element."},{"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.","cause":"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.","error":"TypeError: Cannot read properties of undefined (reading 'displayName')"},{"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.","cause":"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.","error":"Property 'onPostActivate' does not exist on type 'FocusTrapOptions'."}],"ecosystem":"npm"}