Last active
June 10, 2025 04:30
-
-
Save xantiagoma/06b0b8f6dc2d36f876df1be6c7150d77 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
/** | |
* Hook that prevents auto-focus behavior while still maintaining focus management. | |
* Useful for modal dialogs where you want to control the initial focus. | |
* | |
* @template E - Element type, defaults to HTMLDivElement | |
* @returns Object containing: | |
* - ref: React ref to attach to the element | |
* - onOpenAutoFocus: Event handler to prevent default focus behavior | |
* - tabIndex: -1 to make element focusable | |
*/ | |
export function usePreventAutoFocus<E extends HTMLElement = HTMLDivElement>() { | |
const ref = React.useRef<E>(null); | |
const onOpenAutoFocus = React.useCallback((event: Event) => { | |
event.preventDefault(); | |
ref.current?.focus({ preventScroll: true }); | |
}, []); | |
return { ref, onOpenAutoFocus, tabIndex: -1 as const }; | |
} | |
/** | |
<DialogContent | |
className="[&>button]:hidden w-[90vw] max-w-none h-[90vh] max-h-none p-0 focus:outline-none" | |
{...preventAutoFocus} | |
> | |
**/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment