Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

Vadorequest commented Mar 9, 2021

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;

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