Create `useFocusLock` hook
Closed this issue · 1 comments
leroykorterink commented
We should have a util that makes it easy to lock focus inside a ref
. The hook will most likely be used in modal components.
The hook should work with elements from state and RefObjects, the hook shouldn't have any additional properties.
Function signature
function useFocusLock(target: Unreffable<HTMLElement>): void;
Portal example
import { createPortal } from 'react-dom';
import { useFocusLock } from '@mediamonks/react-hooks';
import styles from './Modal.module.scss';
export type ModalProps = {
onClose(): void;
}
export const Modal = ensuredForwardRef<ModalProps, HTMLDivElement>(({ onClose }, ref): ReactNode => {
useFocusLock(ref);
return (
<>
{createPortal(
<div ref={ref} className={styles.modal}>My modal content</div>,
document.querySelector("#modal")!
)}
</>
);
});
leroykorterink commented
We should not create this hook, the native <dialog>
element should be used instead when focus lock is needed. The browser will lock focus and will autofocus the first element inside the dialog automatically, when a dialog is closed focus is returned accordingly as well.