React Focus Trap
A react component to trap your focus for keyboard events.
It is as simple as wrapping your component with the FocusTrap and rest will be be taken care of.
Installation
Using npm:
$ npm i react-focus-trap
Usage
There are 2 ways in which you can use it.
1) Wrapping a component in it.
The default query selector is [role="button"]
but you can pass whatever your application sees fit.
<FocusTrap>
<Modal.Body>
// Do Something
</Modal.Body>
</FocusTrap>
<FocusTrap querySelector={'div.highlighted > p'}>
// Do something / wrap any component
</FocusTrap>
2) Directly calling the method on keybaord events.
The package also exposes focusTrap = (event: KeyboardEvent, elements: HTMLElement[])
function which can be used directly on teh keyboard events.
Just pass the event and the elementList you need to be focus trapped.
const allButtonEls = document.querySelectorAll('[role="button"]')
const onKeyDown = event => focusTrap(event, allButtonEls)
return (
<div onKeyDown={onKeyDown}>
// Do something
</div>
)