Security News
Internet Archive Hacked, 31 Million Record Compromised
The Internet Archive's "Wayback Machine" has been hacked and defaced, with 31 millions records compromised.
react-focus-lock
Advanced tools
The react-focus-lock package is a React component designed to trap focus within a DOM element. It is commonly used to ensure that keyboard users can navigate modal dialogs and other pop-up UI elements without accidentally interacting with the rest of the page.
Focus Trapping
This feature traps the focus within the modal dialog. When the modal is open, the focus cycles through the interactive elements inside the modal and does not move to the background elements.
{"import React from 'react';\nimport FocusLock from 'react-focus-lock';\n\nconst Modal = ({ onClose }) => (\n <FocusLock>\n <div className='modal'>\n <button onClick={onClose}>Close</button>\n {/* other modal contents */}\n </div>\n </FocusLock>\n);"}
AutoFocus and Return Focus
This feature automatically focuses the first focusable element within the FocusLock on mount and returns the focus to the initially focused element when the FocusLock is unmounted.
{"import React from 'react';\nimport FocusLock from 'react-focus-lock';\n\nconst Modal = ({ onClose }) => (\n <FocusLock autoFocus={true} returnFocus={true}>\n <div className='modal'>\n <button onClick={onClose}>Close</button>\n {/* other modal contents */}\n </div>\n </FocusLock>\n);"}
Focus Grouping
This feature allows grouping of focusable elements. Focus can be moved inside a group, and it will be contained within the elements of that group.
{"import React from 'react';\nimport FocusLock, { MoveFocusInside } from 'react-focus-lock';\n\nconst Group = () => (\n <div>\n <MoveFocusInside>\n <button>Button1</button>\n </MoveFocusInside>\n <MoveFocusInside>\n <button>Button2</button>\n </MoveFocusInside>\n </div>\n);\n\nconst App = () => (\n <FocusLock group='group1'>\n <Group />\n </FocusLock>\n);"}
react-modal is a package that provides accessible modals for React applications. It includes the ability to trap focus within the modal, similar to react-focus-lock, but it is specifically designed for modal dialog creation and management.
react-aria-modal is a fully accessible React modal component that manages focus. It also traps focus within the modal, similar to react-focus-lock, and provides a comprehensive solution for creating accessible modals with ARIA attributes.
react-trap-focus is a package that provides focus trapping functionality. It is similar to react-focus-lock in that it traps focus within a specified element, but it may have different implementation details or additional features.
It is a trap! We got your focus and will not let him out!
a11y
is asking for.
Trusted by Atlassian AtlasKit, ReachUI, SmoothUI, Storybook and we will do our best to earn your trust too!
💡 focus locks is part of a bigger whole, consider scroll lock and text-to-speech lock you have to use to really "lock" the user. Try react-focus-on to archive everything above, assembled in the right order.
Just wrap something with focus lock, and focus will be moved inside
on mount.
import FocusLock from 'react-focus-lock';
const JailForAFocus = ({onClose}) => (
<FocusLock>
You can not leave this form
<button onClick={onClose} />
</FocusLock>
);
Demo - https://codesandbox.io/s/5wmrwlvxv4.
FocusLock would work perfectly even with no props set.
FocusLock has few props to tune behavior, all props are optional:
disabled
, to disable(enable) behavior without altering the tree.className
, to set the className
of the internal wrapper.returnFocus
, to return focus into initial position on unmountBy default
returnFocus
is disabled, so FocusLock will not restore original focus on deactivation. This was done mostly to avoid breaking changes. We strong recommend enabling it, to provide a better user experience.
This is expected behavior for Modals, but it is better to implement it by your self. See unmounting and focus management for details
persistentFocus=false
, requires any element to be focused. This also disables text selections inside, and outside focus lock.autoFocus=true
, enables or disables focusing into on Lock activation. If disabled Lock will blur an active focus.noFocusGuards=false
disabled focus guards - virtual inputs which secure tab index.group='''
named focus group for focus scattering aka combined lock targetsshards=[]
an array of ref
pointing to the nodes, which focus lock should consider and a part of it. This is another way focus scattering.whiteList=fn
you could whitelist locations FocusLock should carry about. Everything outside it will ignore. For example - any modals.as='div'
if you need to change internal div
element, to any other. Use ref forwarding to give FocusLock the node to work with.lockProps={}
to pass any extra props (except className) to the internal wrapper.hasPositiveIndices=false
to support a focus lock behavior when any elements tabIndex greater than 0.crossFrame=true
enables aggressive focus capturing within iframesFocus lock exposes a few methods to control focus programmatically.
useFocusInside(nodeRef)
- to move focus inside the given nodeuseFocusScope():{autofocus, focusNext, focusPrev}
- provides API to manage focus within the current lockuseFocusState()
- manages focus state of a given nodeuseFocusController(nodeRef)
- low level version of useFocusScope
working without FocusLock<AutoFocusInside/>
- causes autofocus to look inside the component<MoveFocusInside/>
- wrapper around useFocusInside
, forcibly moves focus inside on mount<FreeFocusInside/>
- hides internals from FocusLock allowing unmanaged focusFocus-lock behavior can be controlled via data-attributes. Declarative API above is working by setting them for you. See corresponding section in focus-lock for details
By default tabbing
in OSX sees
only controls, but not links or anything else tabbable
. This is system settings, and Safari/Firefox obey.
Press Option+Tab in Safari to loop across all tabbables, or change the Safari settings. There is no way to fix Firefox, unless change system settings (Control+F7). See this issue for more information.
react-focus-lock
exposed 3 entry points: for the classical usage, and a sidecar one.
import FocusLock from 'react-focus-lock
would give you component you are looking for.Meanwhile - you dont need any focus related logic until it's needed. Thus - you may defer that logic till Lock activation and move all related code to a sidecar.
import FocusLockUI from 'react-focus-lock/UI
- a DOM part of a lock.import Sidecar from 'react-focus-lock/sidecar
- which is the real focus lock.import FocusLockUI from "react-focus-lock/UI";
import {sidecar} from "use-sidecar";
// prefetch sidecar. data would be loaded, but js would not be executed
const FocusLockSidecar = sidecar(
() => import(/* webpackPrefetch: true */ "react-focus-lock/sidecar")
);
<FocusLockUI
disabled={this.state.disabled}
sideCar={FocusLockSidecar}
>
{content}
</FocusLockUI>
That would split FocusLock into two pieces, reducing app size and improving the first load. The cost of focus-lock is just 1.5kb!
Saved 3.5kb?! 🤷♂️ 3.5kb here and 3.5kb here, and your 20mb bundle is ready.
Use when you cannot use the native autoFocus
prop - because you only want to autofocus once the Trap has been activated
data-autofocus
on the element.data-autofocus-inside
on the element to focus on something inside.AutoFocusInside
component, as named export of this library. import FocusLock, { AutoFocusInside } from 'react-focus-lock';
<FocusLock>
<button>Click</button>
<AutoFocusInside>
<button>will be focused</button>
</AutoFocusInside>
</FocusLock>
// is the same as
<FocusLock>
<button>Click</button>
<button data-autofocus>will be focused</button>
</FocusLock>
If there is more than one auto-focusable target - the first will be selected. If it is a part of radio group, and rest of radio group element are also autofocusable(just put them into AutoFocusInside) - checked one fill be selected.
AutoFocusInside
will work only on Lock activation, and does nothing, then used outside of the lock.
You can use MoveFocusInside
to move focus inside with or without lock.
import { MoveFocusInside } from 'react-focus-lock';
<MoveFocusInside>
<button>will be focused</button>
</MoveFocusInside>
Use focus scattering to handle portals
groups
. Just create a few locks (only one could be active) with a same group nameconst PortaledElement = () => (
<FocusLock group="group42" disabled={true}>
// "discoverable" portaled content
</FocusLock>
);
<FocusLock group="group42">
// main content
</FocusLock>
shards
. Just pass all the pieces to the "shards" prop.const PortaledElement = () => (
<div ref={ref}>
// "discoverable" portaled content
</div>
);
<FocusLock shards={[ref]}>
// main content
</FocusLock>
const PortaledElement = () => (
<div>
// NON-"discoverable" portaled content
</div>
);
<FocusLock shards={[ref]}>
// main content
<PortaledElement />
</FocusLock>
Components
You may use as
prop to change what Focus-Lock will render around children
.
<FocusLock as="section">
<button>Click</button>
<button data-autofocus>will be focused</button>
</FocusLock>
<FocusLock as={AnotherComponent} lockProps={{anyAnotherComponentProp: 4}}>
<button>Click</button>
<span>Hello there!</span>
</FocusLock>
Let's take a look at the Rowing Focus
as an example.
// Will set tabindex to -1 when is not focused
const FocusTrackingButton = ({ children }) => {
const { active, onFocus, ref } = useFocusState();
return (
<button tabIndex={active ? undefined : -1} onFocus={onFocus} ref={ref}>
{children}
</button>
);
};
const RowingFocusInternalTrap = () => {
const { autoFocus, focusNext, focusPrev } = useFocusScope();
// use useFocusController(divRef) if there is no FocusLock around
useEffect(() => {
autoFocus();
}, []);
const onKey = (event) => {
if (event.key === 'ArrowDown') {
focusNext({ onlyTabbable: false });
}
if (event.key === 'ArrowUp') {
focusPrev({ onlyTabbable: false });
}
};
return (
<div
onKeyDown={onKey}
// ref={divRef} for useFocusController
>
<FocusButton>Button1</FocusButton>
<FocusButton>Button2</FocusButton>
<FocusButton>Button3</FocusButton>
<FocusButton>Button4</FocusButton>
</div>
);
};
// FocusLock, even disabled one
const RowingFocusTrap = () => (
<FocusLock disabled>
<RowingFocusInternalTrap />
</FocusLock>
);
As you may know - FocusLock is adding Focus Guards
before and after lock to remove some side effects, like page scrolling.
But shards
will not have such guards, and it might be not so cool to use them - for example if no tabbable
would be
defined after shard - you will tab to the browser chrome.
You may wrap shard with InFocusGuard
or just drop InFocusGuard
here and there - that would solve the problem.
import {InFocusGuard} from 'react-focus-lock';
// wrap with
<InFocusGuard>
<button />
</InFocusGuard>
// place before and after
<InFocusGuard />
<button />
<InFocusGuard />
InFocusGuards would be active(tabbable) only when tabble, it protecting, is focused.
If only your modal is the last tabble element on the body - you might remove the Tailing Guard, to allow user tab into address bar.
<InFocusGuard/>
<button />
// there is no "tailing" guard :)
returnFocus
enabled, and it's going to be unmounted - focus will be returned after zero-timeout.returnFocus
is set to false
, and you are going to control focus change on your own - keep in mindReact will first call Parent.componentWillUnmount, and next Child.componentWillUnmount
This means - Trap will be still active by the time you may want move(return) focus on componentWillUnmount. Please deffer this action with a zero-timeout.
Similarly, if you are using the disabled
prop to control FocusLock, you will need a zero-timeout to correctly restore focus.
<FocusLock
disabled={isFocusLockDisabled}
onDeactivation={() => {
// Without the zero-timeout, focus will likely remain on the button/control
// you used to set isFocusLockDisabled = true
window.setTimeout(() => myRef.current.focus(), 0);
}
>
In some cases the original node that was focused before the lock was activated is not the desired node to return focus to. Some times this node might not exists at all.
returnFocus
, letting you decide where to return focus to.<FocusLock
returnFocus={(suggestedNode) => {
// somehow activeElement should not be changed
if(document.activeElement.hasAttributes('main-content')) {
// opt out from default behavior
return false;
}
if (someCondition(suggestedNode)) {
// proceed with the suggested node
return true;
}
// handle return focus manually
document.getElementById('the-button').focus();
// opt out from default behavior
return false;
}}
/>
read more at the issue #83 or mdn article.
To return focus, but without jumpy page scroll returning a focus you might specify a focus option
<FocusLock
returnFocus={{ preventScroll: false }} // working not in all browsers
>
Not supported by Edge and Safari.
Two different focus-lock-managers or even different version of a single one, being active simultaneously will FIGHT for the focus. This usually totally breaks user experience.
React-Focus-Lock will automatically surrender, letting another library to take the lead.
You may wrap some render branch with FreeFocusInside
, and react-focus-lock will ignore
any focus inside marked node. So in case focus moves to uncontrolled location focus-lock will not trigger letting another library to act without interference in that another location.
import { FreeFocusInside } from 'react-focus-lock';
<FreeFocusInside>
<div id="portal-for-modals">
in this div i am going to portal my modals, dont fight with them please
</div>
</FreeFocusInside>
Another option for hybrid applications is to whiteList
area where Focus-Lock should act, automatically allowing other managers in other areas.
The code below will scope Focus-Lock on inside the (react)root
element, so anything jQuery can add to the body will be ignored.
<FocusLock whiteList={node => document.getElementById('root').contains(node)}>
...
</FocusLock>
React-Focus-Lock is expected to be a singlentone. __Use webpack or yarn resolution for force only one version of react-focus-lock used.
webpack.conf
resolve: {
alias: {
'react-focus-lock': path.resolve(path.join(__dirname, './node_modules/react-focus-lock'))
...
From MDN Article about accessible dialogs:
This one is about managing the focus.
I've got a good article about focus management, dialogs and WAI-ARIA.
Uses focus-lock under the hood. It does also provide support for Vue.js and Vanilla DOM solutions
To create a "right" modal dialog you have to:
You may use react-focus-on to achieve everything above, assembled in the right order.
MIT
FAQs
It is a trap! (for a focus)
The npm package react-focus-lock receives a total of 1,750,095 weekly downloads. As such, react-focus-lock popularity was classified as popular.
We found that react-focus-lock demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
The Internet Archive's "Wayback Machine" has been hacked and defaced, with 31 millions records compromised.
Security News
TC39 is meeting in Tokyo this week and they have approved nearly a dozen proposals to advance to the next stages.
Security News
Our threat research team breaks down two malicious npm packages designed to exploit developer trust, steal your data, and destroy data on your machine.