Skip to content

Instantly share code, notes, and snippets.

@xantiagoma
Last active June 10, 2025 04:30
Show Gist options
  • Save xantiagoma/06b0b8f6dc2d36f876df1be6c7150d77 to your computer and use it in GitHub Desktop.
Save xantiagoma/06b0b8f6dc2d36f876df1be6c7150d77 to your computer and use it in GitHub Desktop.
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