focus-lock vs react-focus-lock vs react-focus-trap
Focus Management in Web Applications Comparison
3 Years
focus-lockreact-focus-lockreact-focus-trapSimilar Packages:
What's Focus Management in Web Applications?

Focus management libraries help developers control keyboard focus within web applications, ensuring that users, especially those relying on assistive technologies, can navigate interfaces efficiently. These libraries are essential for creating accessible modals, dialogs, and interactive components by managing where the focus goes when a component is opened or closed. They help prevent focus from escaping a designated area, which is crucial for maintaining context and usability, particularly for users who navigate with keyboards or screen readers. focus-lock is a lightweight, framework-agnostic library that provides simple focus trapping capabilities, while react-focus-lock and react-focus-trap are React-specific implementations that offer more features and integration with React's lifecycle.

Package Weekly Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
focus-lock2,340,900
181188 kB08 months agoMIT
react-focus-lock2,093,134
1,373111 kB117 months agoMIT
react-focus-trap5,294
8014.6 kB9-MIT
Feature Comparison: focus-lock vs react-focus-lock vs react-focus-trap

Framework Compatibility

  • focus-lock:

    focus-lock is a framework-agnostic library, meaning it can be used with any web application regardless of the framework or library being used. This makes it highly versatile and suitable for both vanilla JavaScript projects and those built with frameworks like React, Vue, or Angular.

  • react-focus-lock:

    react-focus-lock is specifically designed for React applications. It leverages React's component model to manage focus, making it easy to integrate into any React project. Its API is tailored for React, which may limit its use in non-React environments but provides a more seamless experience for React developers.

  • react-focus-trap:

    react-focus-trap is also a React-specific library, providing a more comprehensive solution for managing focus within React components. It offers more features and flexibility compared to react-focus-lock, making it suitable for complex React applications that require detailed control over focus behavior.

Ease of Integration

  • focus-lock:

    focus-lock is easy to integrate into any web application. Its simple API and minimal setup requirements allow developers to quickly implement focus trapping without significant changes to their existing codebase.

  • react-focus-lock:

    react-focus-lock offers straightforward integration for React developers. Its component-based approach allows for quick implementation within React components, and its documentation provides clear guidance on how to use it effectively.

  • react-focus-trap:

    react-focus-trap provides detailed documentation and examples, making it easy for developers to understand and implement its features. However, its more complex API may require a bit more time to fully grasp, especially for those new to focus management.

Customization and Flexibility

  • focus-lock:

    focus-lock provides basic customization options, such as specifying which elements can receive focus and defining callbacks for when focus is locked or released. However, it is relatively simple and does not offer extensive customization features.

  • react-focus-lock:

    react-focus-lock allows for some customization, such as defining which elements should be focusable and providing callbacks for focus events. It is designed to be flexible while maintaining a straightforward API that is easy to use.

  • react-focus-trap:

    react-focus-trap offers the most customization and flexibility among the three. It allows developers to define complex focus trapping behaviors, including nested traps, custom focus handling, and more. This makes it the best choice for applications that require detailed control over how focus is managed.

Accessibility Features

  • focus-lock:

    focus-lock is designed with accessibility in mind, ensuring that focus is managed in a way that is friendly to keyboard users and assistive technologies. However, it does not provide extensive built-in features for managing accessibility beyond basic focus trapping.

  • react-focus-lock:

    react-focus-lock prioritizes accessibility by ensuring that focus is trapped within the designated area, preventing focus from escaping and helping users navigate more easily. It follows ARIA guidelines and is designed to work well with screen readers and keyboard navigation.

  • react-focus-trap:

    react-focus-trap also focuses on accessibility, providing features that ensure compliant focus management. It includes support for ARIA attributes and allows developers to implement accessible focus trapping that works seamlessly with assistive technologies.

Code Example

  • focus-lock:

    Basic usage of focus-lock

    <div id="modal" role="dialog" aria-modal="true">
      <h2>Modal Title</h2>
      <input type="text" placeholder="First Name" />
      <input type="text" placeholder="Last Name" />
      <button id="close">Close</button>
    </div>
    
    <script src="https://unpkg.com/focus-lock/dist/focus-lock.umd.js"></script>
    <script>
      const modal = document.getElementById('modal');
      const closeButton = document.getElementById('close');
    
      // Lock focus within the modal
      focusLock(modal);
    
      closeButton.addEventListener('click', () => {
        // Unlock focus when closing the modal
        focusLock.unlock();
        modal.style.display = 'none';
      });
    </script>
    
  • react-focus-lock:

    Basic usage of react-focus-lock

    import React from 'react';
    import FocusLock from 'react-focus-lock';
    
    function Modal() {
      return (
        <FocusLock>
          <div role="dialog" aria-modal="true">
            <h2>Modal Title</h2>
            <input type="text" placeholder="First Name" />
            <input type="text" placeholder="Last Name" />
            <button>Close</button>
          </div>
        </FocusLock>
      );
    }
    
    export default Modal;
    
  • react-focus-trap:

    Basic usage of react-focus-trap

    import React from 'react';
    import FocusTrap from 'react-focus-trap';
    
    function Modal() {
      return (
        <FocusTrap>
          <div role="dialog" aria-modal="true">
            <h2>Modal Title</h2>
            <input type="text" placeholder="First Name" />
            <input type="text" placeholder="Last Name" />
            <button>Close</button>
          </div>
        </FocusTrap>
      );
    }
    
    export default Modal;
    
How to Choose: focus-lock vs react-focus-lock vs react-focus-trap
  • focus-lock:

    Choose focus-lock if you need a lightweight, framework-agnostic solution for trapping focus in any web application. It is ideal for simple implementations where you want to ensure focus stays within a specific element, such as a modal or dialog, without the overhead of a larger library.

  • react-focus-lock:

    Select react-focus-lock if you are building a React application and need a straightforward way to manage focus within components. It is easy to integrate and provides a clean API for locking focus, making it suitable for modals, popovers, and other interactive elements.

  • react-focus-trap:

    Opt for react-focus-trap if you require a more feature-rich solution for focus management in React applications. It offers advanced capabilities like handling nested traps, managing focus on component mount and unmount, and providing more control over focus behavior, making it ideal for complex interfaces that demand precise focus management.

README for focus-lock

focus-lock

It is a trap! We got your focus and will not let him out!

NPM

Important - this is a low level package to be used in order to create "focus lock". It does not provide any "lock" capabilities by itself, only helpers you can use to create one

Focus-lock implementations

This is a base package for:

The common use case will look like final realization.

import { moveFocusInside, focusInside } from 'focus-lock';

if (someNode && !focusInside(someNode)) {
  moveFocusInside(someNode, lastActiveFocus /* very important to know */);
}

note that tracking lastActiveFocus is on the end user.

Declarative control

focus-lock provides not only API to be called by some other scripts, but also a way one can leave instructions inside HTML markup to amend focus behavior in a desired way.

These are data-attributes one can add on the elements:

  • control
    • data-focus-lock=[group-name] to create a focus group (scattered focus)
    • data-focus-lock-disabled="disabled" marks such group as disabled and removes from the list. Equal to removing elements from the DOM.
    • data-no-focus-lock focus-lock will ignore/allow focus inside marked area. Focus on this elements will not be managed by focus-lock.
  • autofocus (via moveFocusInside(someNode, null))
    • data-autofocus will autofocus marked element on activation.
    • data-autofocus-inside focus-lock will try to autofocus elements within selected area on activation.
    • data-no-autofocus focus-lock will not autofocus any node within marked area on activation.

These markers are available as import * as markers from 'focus-lock/constants'

Additional API

Get focusable nodes

Returns visible and focusable nodes

import { expandFocusableNodes, getFocusableNodes, getTabbleNodes } from 'focus-lock';

// returns all focusable nodes inside given locations
getFocusableNodes([many, nodes])[0].node.focus();

// returns all nodes reacheable in the "taborder" inside given locations
getTabbleNodes([many, nodes])[0].node.focus();

// returns an "extended information" about focusable nodes inside. To be used for advances cases (react-focus-lock)
expandFocusableNodes(singleNodes);

Programmatic focus management

Allows moving back and forth between focusable/tabbable elements

import { focusNextElement, focusPrevElement } from 'focus-lock';
focusNextElement(document.activeElement, {
  scope: theBoundingDOMNode,
}); // -> next tabbable element

Return focus

Advanced API to return focus (from the Modal) to the last or the next best location

import { captureFocusRestore } from 'focus-lock';
const restore = captureFocusRestore(element);
// ....
restore()?.focus(); // restores focus the the element, or it's siblings in case it no longer exists

WHY?

From MDN Article about accessible dialogs:

  • The dialog must be properly labeled
  • Keyboard focus must be managed correctly

This one is about managing the focus.

I'v got a good article about focus management, dialogs and WAI-ARIA.

Focus fighting

It is possible, that more that one "focus management system" is present on the site. For example, you are using FocusLock for your content, and also using some Modal dialog, with FocusTrap inside.

Both system will try to do their best, and move focus into their managed areas. Stack overflow. Both are dead.

Focus Lock(React-Focus-Lock, Vue-Focus-Lock and so on) implements anti-fighting protection - once the battle is detected focus-lock will surrender(as long there is no way to win this fight).

You may also land a peace by special data attribute - data-no-focus-lock(constants.FOCUS_ALLOW). It will remove focus management from all nested elements, letting you open modals, forms, or use any third party component safely. Focus lock will just do nothing, while focus is on the marked elements.

API

default(topNode, lastNode) (aka setFocus), moves focus inside topNode, keeping in mind that last focus inside was - lastNode

Licence

MIT