Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/davidtheclark/focus-trap-react
A React component that traps focus
https://github.com/davidtheclark/focus-trap-react
dependabot focus-trap react-a11y tappable
Last synced: 3 months ago
JSON representation
A React component that traps focus
- Host: GitHub
- URL: https://github.com/davidtheclark/focus-trap-react
- Owner: focus-trap
- License: mit
- Created: 2015-08-15T18:55:44.000Z (about 9 years ago)
- Default Branch: master
- Last Pushed: 2024-04-10T17:15:52.000Z (7 months ago)
- Last Synced: 2024-04-16T21:06:25.146Z (7 months ago)
- Topics: dependabot, focus-trap, react-a11y, tappable
- Language: JavaScript
- Homepage: http://focus-trap.github.io/focus-trap-react/demo/
- Size: 6.43 MB
- Stars: 693
- Watchers: 4
- Forks: 70
- Open Issues: 4
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
- Code of conduct: CODE_OF_CONDUCT.MD
- Security: SECURITY.md
Awesome Lists containing this project
README
# focus-trap-react [![CI](https://github.com/focus-trap/focus-trap-react/workflows/CI/badge.svg?branch=master&event=push)](https://github.com/focus-trap/focus-trap-react/actions?query=workflow:CI+branch:master) [![Codecov](https://img.shields.io/codecov/c/github/focus-trap/focus-trap-react)](https://codecov.io/gh/focus-trap/focus-trap-react) [![license](https://badgen.now.sh/badge/license/MIT)](./LICENSE)
[![All Contributors](https://img.shields.io/badge/all_contributors-28-orange.svg?style=flat-square)](#contributors)
A React component that traps focus.
This component is a light wrapper around [focus-trap](https://github.com/focus-trap/focus-trap),
tailored to your React-specific needs.You might want it for, say, building [an accessible modal](https://github.com/davidtheclark/react-aria-modal)?
## What it does
[Check out the demo](http://focus-trap.github.io/focus-trap-react/demo/).
Please read [the focus-trap documentation](https://github.com/focus-trap/focus-trap) to understand what a focus trap is, what happens when a focus trap is activated, and what happens when one is deactivated.
This module simply provides a React component that creates and manages a focus trap.
- The focus trap automatically activates when mounted (by default, though this can be changed).
- The focus trap automatically deactivates when unmounted.
- The focus trap can be activated and deactivated, paused and unpaused via props.## Installation
```
npm install focus-trap-react
````dist/focus-trap-react.js` is the Babel-compiled file that you'll use.
### React dependency
React `>= 16.3.0`
## Browser Support
As old and as broad as _reasonably_ possible, excluding browsers that are out of support or have nearly no user base.
Focused on desktop browsers, particularly Chrome, Edge, FireFox, Safari, and Opera.
Focus-trap-react is not officially tested on any mobile browsers or devices.
> β οΈ Microsoft [no longer supports](https://blogs.windows.com/windowsexperience/2022/06/15/internet-explorer-11-has-retired-and-is-officially-out-of-support-what-you-need-to-know/) any version of IE, so IE is no longer supported by this library.
> π¬ Focus-trap-react relies on focus-trap so its browser support is at least [what focus-trap supports](https://github.com/focus-trap/focus-trap#browser-support).
> π¬ Keep in mind that performance optimization and old browser support are often at odds, so tabbable may not always be able to use the most optimal (typically modern) APIs in all cases.
## Usage
You wrap any element that you want to act as a focus trap with the `` component. `` expects exactly one child element which can be any HTML element or other React component that contains focusable elements. __It cannot be a Fragment__ because `` needs to be able to get a reference to the underlying HTML element, and Fragments do not have any representation in the DOM.
For example:
```js
Ok
Cancel
```
```js
```
You can read further code examples in `demo/` (it's very simple), and [see how it works](http://focus-trap.github.io/focus-trap-react/demo/).
Here's one more simple example:
```jsx
const React = require('react');
const ReactDOM = require('react-dom'); // React 16-17
const { createRoot } = require('react-dom/client'); // React 18
const FocusTrap = require('focus-trap-react');class Demo extends React.Component {
constructor(props) {
super(props);this.state = {
activeTrap: false
};this.mountTrap = this.mountTrap.bind(this);
this.unmountTrap = this.unmountTrap.bind(this);
}mountTrap = () => {
this.setState({ activeTrap: true });
};unmountTrap = () => {
this.setState({ activeTrap: false });
};render() {
const trap = this.state.activeTrap
?
: false;return (
activate trap
{trap}
);
}
}ReactDOM.render(, document.getElementById('root')); // React 16-17
createRoot(document.getElementById('root')).render(); // React 18
```## βοΈβοΈ React 18 Strict Mode βοΈβοΈ
React 18 introduced [new behavior](https://reactjs.org/docs/strict-mode.html#ensuring-reusable-state) in Strict Mode whereby it mimics a possible future behavior where React might optimize an app's performance by unmounting certain components that aren't in use and later remounting them with previous, reused state when the user needs them again. What constitutes "not in use" and "needs them again" is as yet undefined.
_Remounted with reused state_ is the key difference between what is otherwise expected about [unmounted components](https://reactjs.org/docs/react-component.html#componentwillunmount).
__[v9.0.2](https://github.com/focus-trap/focus-trap-react/pull/721) adds support__ for this new Strict Mode behavior: The trap attempts to detect that it has been remounted with previous state: If the `active` prop's value is `true`, and an internal focus trap instance already exists, the focus trap is re-activated on remount in order to reconcile stated expectations.
> π¨ In Strict Mode (and so in dev builds only, since this behavior of Strict Mode only affects dev builds), the trap __will be deactivated as soon as it is mounted__, and then reactivated again, almost immediately, because React will immediately unmount and remount the trap as soon as it's rendered.
Therefore, __avoid using options like onActivate, onPostActivate, onDeactivate, or onPostDeactivate to affect component state__.
Explanation and sample anti-pattern to avoid
See this discussion for an example sandbox (issue description) whereonDeactivate
was used to trigger the close of a dialog when the trap was deactivated (e.g. to react to the user clicking outside the trap withfocusTrapOptions.clickOutsideDeactivates=true
).
The result can be that (depending on how you render the trap) in Strict Mode, the dialog never appears because it gets closed as soon as the trap renders, since the trap is deactivated as soon as it's unmounted, and so theonDeactivate
handler is called, thus hiding the dialog...
This is intentional: If the trap gets unmounted, it has no idea if it's being unmounted for good or if it's going to be remounted at some future point in time. It also has no idea of knowing how long it will be until it's remounted again. So it must be deactivated as though it's going away for good in order to prevent unintentional behavior and memory leaks (from orphaned document event listeners).## Props
### children
> β οΈ The `` component requires a __single__ child, and this child must __forward refs__ onto the element which will ultimately be considered the trap's container. Since React does not provide for a way to forward refs to class-based components, this means the child must be a __functional__ component that uses the `React.forwardRef()` API.
>
> If you must use a __class__-based component as the trap's container, then you will need to get your own ref to it upon render, and use the `containerElements` prop (initially set to an empty array `[]`) in order to provide the ref's element to it once updated by React (hint: use a [callback ref](https://reactjs.org/docs/refs-and-the-dom.html#callback-refs)).> π¬ The child is ignored (but still rendered) if the `containerElements` prop is used to imperatively provide trap container elements.
Example:
```jsx
const React = require('react');
const { createRoot } = require('react-dom/client');
const propTypes = require('prop-types');
const FocusTrap = require('../../dist/focus-trap-react');const container = document.getElementById('demo-function-child');
const TrapChild = React.forwardRef(function ({ onDeactivate }, ref) {
return (
);
});TrapChild.displayName = 'TrapChild';
TrapChild.propTypes = {
onDeactivate: propTypes.func,
};class DemoFunctionChild extends React.Component {
constructor(props) {
super(props);this.state = {
activeTrap: false,
};this.mountTrap = this.mountTrap.bind(this);
this.unmountTrap = this.unmountTrap.bind(this);
}mountTrap() {
this.setState({ activeTrap: true });
}unmountTrap() {
this.setState({ activeTrap: false });
}render() {
const trap = this.state.activeTrap && (
);return (
activate trap
{trap}
);
}
}const root = createRoot(container);
root.render();
```### focusTrapOptions
Type: `Object`, optional
Pass any of the options available in focus-trap's [createOptions](https://github.com/focus-trap/focus-trap#createoptions).
> βοΈ This prop is __only read once__ on the first render. It's never looked at again. This is particularly important if you use state-dependent memoized __React Hooks__ (e.g. `const onActivate = useCallback(() => {...}, [something])`) for any of the focus-trap callbacks like `onActivate()`, `onDeactivate()`, `clickOutsideDeactivates()`, etc.
>
> If you need state-dependent callbacks, you have two options: __(1)__ Use a React component `class` (as in the examples in this README) with bound member handlers, or __(2)__ use a React Ref like `useRef({ myState: 1 })` in your callbacks and manually manage your state.
>
> See [#947](https://github.com/focus-trap/focus-trap-react/issues/947) for more details.> β οΈ See notes about __[testing in JSDom](#testing-in-jsdom)__ (e.g. using Jest) if that's what you currently use.
### active
Type: `Boolean`, optional
By default, the `FocusTrap` activates when it mounts. So you activate and deactivate it via mounting and unmounting. If, however, you want to keep the `FocusTrap` mounted *while still toggling its activation state*, you can do that with this prop.
See `demo/demo-special-element.js`.
### paused
Type: `Boolean`, optional
If you would like to pause or unpause the focus trap (see [`focus-trap`'s documentation](https://github.com/focus-trap/focus-trap#focustrappause)), toggle this prop.
### containerElements
Type: `Array of HTMLElement`, optional
If specified, these elements will be used as the boundaries for the focus-trap, __instead of the child__. These get passed as arguments to `focus-trap`'s `updateContainerElements()` method.
> π¬ Note that when you use `containerElements`, the need for a child is eliminated as the child is __always__ ignored (though still rendered) when the prop is specified, even if this prop is `[]` (an empty array).
>
> Also note that if the refs you're putting into the array, like `containerElements={[ref1.current, ref2.current]}`, aren't resolved yet, resulting in `[null, null]` for example, the trap will not get created. The array must contain at least one valid `HTMLElement` in order for the trap to get created/updated.If `containerElements` is subsequently updated (i.e. after the trap has been created) to an empty array (or an array of falsy values like `[null, null]`), the trap will still be active, but the TAB key will do nothing because the trap will not contain any tabbable groups of nodes. At this point, the trap can either be deactivated manually or by unmounting, or an updated set of elements can be given to `containerElements` to resume use of the TAB key.
Using `containerElements` does require the use of React refs which, by nature, will require at least one state update in order to get the resolved elements into the prop, resulting in at least one additional render. In the normal case, this is likely more than acceptable, but if you really want to optimize things, then you could consider [using focus-trap directly](https://codesandbox.io/s/focus-trapreact-containerelements-demos-v5ydi) (see `Trap2.js`).
## Help
### Testing in JSDom
> β οΈ JSDom is not officially supported. Your mileage may vary, and tests may break from one release to the next (even a patch or minor release).
>
> This topic is just here to help with what we know may affect your tests.In general, a focus trap is best tested in a full browser environment such as Cypress, Playwright, or Nightwatch where a full DOM is available.
Sometimes, that's not entirely desirable, and depending on what you're testing, you may be able to get away with using JSDom (e.g. via Jest), but you'll have to configure your traps using the `focusTrapOptions.tabbableOptions.displayCheck: 'none'` option.
See [Testing focus-trap in JSDom](https://github.com/focus-trap/focus-trap#testing-in-jsdom) for more details.
## Contributing
See [CONTRIBUTING](CONTRIBUTING.md).
## Contributors
In alphabetical order:
Alex Dawson
π
Benjamin Koltes
π
Benjamin Tan
π
Clint Goodman
π» π π‘ β οΈ
Daniel
π§ β οΈ
Daniel Tonon
π π» β οΈ
David Clark
π» π π β οΈ π π§
Dependabot
π§
Johannes Ewald
π»
Jonathan Suzuki
π
Kasper Garnæs
π
Kathleen McMahon
π§
LoganDark
π
Marais Rossouw
π
Michael
π‘
Misha Moroshko
π
Nate Liu
β οΈ
Rivaldo Junior
π§
Scott Rippey
π» π
Sean McPherson
π»
Shane Moore
π¦
Slapbox
π π
Stefan Cameron
π» π π β οΈ π π§
Tyler Hawkins
π π‘ β οΈ π§
Wandrille Verlut
π» β οΈ
krikienoid
π
robert-westenberger
π π
syntactic-salt
π