11.0.1 โ€ข Published 10 days ago

focus-trap-react v11.0.1

Weekly downloads
219,027
License
MIT
Repository
github
Last release
10 days ago

focus-trap-react CI Codecov license

All Contributors

A React component that traps focus.

This component is a light wrapper around focus-trap, tailored to your React-specific needs.

You might want it for, say, building an accessible modal?

What it does

Check out the demo.

Please read the focus-trap documentation 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 >= 18.0.0

Note that while React 18.x still supported propTypes and defaultProps, they had long-since been deprecated, and are completely dropped in React 19.

Therefore, this library no longer assigns these properties to the <FocusTrap> element for runtime validation and initialization. The same techniques you would now use in React 19 are backward-compatible with React 18:

  • Use TypeScript for static prop type validation
  • Use a runtime validation library such as RTV.js, JSON Schema, or yup for runtime prop validation to replace prop-types)

This library aims to support one major version of React behind the current major version, since React major releases are typically years apart -- to the extent that the feature drift is not too great and remains reasonably surmountable.

Browser Support

Focused on desktop browsers, particularly Chrome, Edge, FireFox, Safari, and Opera.

Gated by what React supports in the version currently supported.

Focus-trap-react is not officially tested on any mobile browsers or devices.

โš ๏ธ Microsoft no longer supports 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.

๐Ÿ’ฌ 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 <FocusTrap> component. <FocusTrap> 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 <FocusTrap> 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:

<FocusTrap>
  <div id="modal-dialog" className="modal" >
    <button>Ok</button>
    <button>Cancel</button>
  </div>
</FocusTrap>
<FocusTrap>
  <ModalDialog okButtonText="Ok" cancelButtonText="Cancel" />
</FocusTrap>

You can read further code examples in demo/ (it's very simple), and see how it works.

Here's one more simple example:

import React from 'react';
import { createRoot } from 'react-dom/client';
import { FocusTrap } from '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
      ? <FocusTrap
          focusTrapOptions={{
            onDeactivate: this.unmountTrap
          }}
        >
          <div className="trap">
            <p>
              Here is a focus trap
              {' '}
              <a href="#">with</a>
              {' '}
              <a href="#">some</a>
              {' '}
              <a href="#">focusable</a>
              {' '}
              parts.
            </p>
            <p>
              <button onClick={this.unmountTrap}>
                deactivate trap
              </button>
            </p>
          </div>
        </FocusTrap>
      : false;

    return (
      <div>
        <p>
          <button onClick={this.mountTrap}>
            activate trap
          </button>
        </p>
        {trap}
      </div>
    );
  }
}

createRoot(document.getElementById('root')).render(<Demo />); // React 18

โ—๏ธโ—๏ธ React 18 Strict Mode โ—๏ธโ—๏ธ

React 18 introduced new behavior 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.

v9.0.2 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.

Props

children

โš ๏ธ The <FocusTrap> 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).

๐Ÿ’ฌ The child is ignored (but still rendered) if the containerElements prop is used to imperatively provide trap container elements.

Example:

import { forwardRef, Component } from 'react';
import { createRoot } from 'react-dom/client';
import { FocusTrap } from 'focus-trap-react';

const container = document.getElementById('demo-function-child');

const TrapChild = forwardRef(function ({ onDeactivate }, ref) {
  return (
    <div ref={ref}>
      <p>
        Here is a focus trap <a href="#">with</a> <a href="#">some</a>{' '}
        <a href="#">focusable</a> parts.
      </p>
      <p>
        <button
          onClick={onDeactivate}
          aria-describedby="class-child-heading"
        >
          deactivate trap
        </button>
      </p>
    </div>
  );
});

TrapChild.displayName = 'TrapChild';
TrapChild.propTypes = {
  onDeactivate: propTypes.func,
};

class DemoFunctionChild extends 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 && (
      <FocusTrap
        focusTrapOptions={{
          onDeactivate: this.unmountTrap,
        }}
      >
        <TrapChild />
      </FocusTrap>
    );

    return (
      <div>
        <p>
          <button onClick={this.mountTrap} aria-describedby="function-child-heading">
            activate trap
          </button>
        </p>
        {trap}
      </div>
    );
  }
}

const root = createRoot(container);
root.render(<DemoFunctionChild />);

focusTrapOptions

Type: Object, optional

Pass any of the options available in focus-trap's 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 for more details.

โš ๏ธ See notes about 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), 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 (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 for more details.

Contributing

See CONTRIBUTING.

Contributors

In alphabetical order:

volpara-components@lifesum/cms-components@cocolist/thumbprint-react@rh-uxd/integrationamindbootstrap1amindbootstrapnatbootstrap2@luchmewep/mdbreactreact-haaretz-modal-dialogvolpara-uichocolate_swirlreact-ruireact-timelines-vimodquaantum-components@styleless-ui/react-hookscom.sap.designsystem.communitymultisys-design-system@atlastix/euinagwa-html-editornagwa-html-editor-deprecatedfc-gha@talend/react-datagriddemotestpublish@knapsack/tobymeetup-web-components@everything-registry/sub-chunk-1688sashi-swagger-ui-kong-theme-universalsg-swagger-ui-kong-theme-universalsg-swagger-ui-kong-theme-universal-jjjsg-swagger-ui-kong-theme-universal-jtestingsg-swagger-ui-kong-theme-universal-ssssg-swagger-ui-kong-theme-universalssg-swagger-ui-kong-theme-universalsszelar-swagger-ui-kong-themesimplitime-communicationalt-super-great-testing-chat-tempsystema-modalsysotest-header-pkgwebbteamet-componentswtw-accessible-react-datepickersaagie-uishg-cdbsettle_plannersamaelnpmreportcssemente-jsreportelabreport-publishreport-publish-apreact18-aria-modalreactjs-modal-dialogstarr-vitespark-ignitionsentral.rntesting-test-testesttestfabricconnect-widget@bbl-digital/snorre-v2mineral-uimigrateaimodalwh-oc14lookingglass-reactjobiqo-cljobiqo-cl-vanillaibm-dotcom-library-reactinvolv-ui-coreitb_web_playerlouis-mdbreactm7kvqbe1-react-component-librarymdbreactmdbreact-fork-without-momentmdbreact-without-momentmdbreact_pmdbreact_phucmdbreactpro-oussama-fullmedlit-libmoiremon-entreprisemtformsmtxuilibkuali-uikangctkifu-for-jshellostevennebinebula-reactndla-uimy-react-modal-ad62mx-react-componentsmtxtrpcv2mbdpam-frontend-datovelgerorion-pulsarorganism-next-uiorcs-design-systemownaipractical-react-components-corepretty-modalproptokenplaid-threads
11.0.0

15 days ago

11.0.1

10 days ago

10.3.1

1 month ago

10.3.0

3 months ago

10.2.3

1 year ago

10.2.2

1 year ago

10.2.1

1 year ago

10.1.4

2 years ago

10.1.3

2 years ago

10.1.2

2 years ago

10.1.0

2 years ago

10.1.1

2 years ago

10.0.1

2 years ago

10.0.2

2 years ago

10.0.0

2 years ago

8.11.3

3 years ago

8.11.2

3 years ago

9.0.2

3 years ago

9.0.1

3 years ago

9.0.0

3 years ago

8.11.1

3 years ago

8.11.0

3 years ago

8.10.0

3 years ago

8.9.0

3 years ago

8.9.2

3 years ago

8.9.1

3 years ago

8.8.2

3 years ago

8.8.1

3 years ago

8.8.0

3 years ago

8.7.1

3 years ago

8.7.0

3 years ago

8.6.0

4 years ago

8.5.1

4 years ago

8.5.0

4 years ago

8.4.2

4 years ago

8.4.1

4 years ago

8.4.0

4 years ago

8.3.2

4 years ago

8.3.1

4 years ago

8.3.0

4 years ago

8.2.0

4 years ago

8.1.1

4 years ago

8.1.0

4 years ago

8.0.0

4 years ago

7.0.1

4 years ago

7.0.0

4 years ago

6.0.0

6 years ago

5.0.1

6 years ago

5.0.0

6 years ago

4.0.1

6 years ago

4.0.0

6 years ago

3.1.4

6 years ago

3.1.3

6 years ago

3.1.2

7 years ago

3.1.1

7 years ago

3.1.0

7 years ago

3.0.5

7 years ago

3.0.4

7 years ago

3.0.3

8 years ago

3.0.2

8 years ago

3.0.1

9 years ago

3.0.0

9 years ago

2.1.1

9 years ago

2.1.0

9 years ago

2.0.1

9 years ago

2.0.0

9 years ago

1.0.0

9 years ago

0.2.1

9 years ago

0.2.0

9 years ago

0.1.0

9 years ago