• Custom React hook that traps focus within a specified element.

    When enabled, the hook will focus the first focusable child of the parent element on mount. When disabled, it will return focus to the previously focused element. It also handles the Tab key navigation to loop the focus within the child elements.

    Example

    const MyComponent = () => {
    const ref = useRef<HTMLDivElement>(null);
    useFocusTrap(ref);

    return (
    <>
    <div ref={ref} tabIndex={0}>
    <input type="text" placeholder="Input 1" />
    <input type="text" placeholder="Input 2" />
    <button>Submit</button>
    </div>

    <button>Outside button</button>
    </>
    );
    };

    Parameters

    • ref: RefObject<HTMLElement>

      A reference to the element to trap focus within.

    • optionsProps: IUseFocusTrapProps = {}

      Optional settings for managing focus trap behavior.

    Returns void