Skip to content

Instantly share code, notes, and snippets.

@carpben
Created August 10, 2019 04:52
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save carpben/de968e377cbac0ffbdefe1ab56237573 to your computer and use it in GitHub Desktop.
Save carpben/de968e377cbac0ffbdefe1ab56237573 to your computer and use it in GitHub Desktop.
useFocus.ts
export const useFocus = () => {
const htmlElRef = useRef<HTMLElement>()
const setFocus = () => {
const currentEl = htmlElRef.current
currentEl && currentEl.focus()
}
return [setFocus, htmlElRef] as const
}
@Vadorequest
Copy link

A bit better:

import {
  MutableRefObject,
  useRef,
} from 'react';

const useFocus = (): [any, () => void] => {
  const htmlElRef: MutableRefObject<any> = useRef(null);
  const setFocus = (): void => {
    htmlElRef?.current?.focus?.();
  };

  return [htmlElRef, setFocus];
};

export default useFocus;

@55Cancri
Copy link

55Cancri commented Feb 8, 2023

Even better:

export default function useFocus<T extends HTMLElement = HTMLElement>() {
  const ref = React.useRef<T>(null);
  const setFocus = () => ref?.current?.focus?.();

  return [ref, setFocus] as const;
}

and use like:

const [focusRef, setFocus] = useFocus<HTMLButtonElement>();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment