Skip to content

Instantly share code, notes, and snippets.

@zhammer
Created April 5, 2019 13:13
Show Gist options
  • Save zhammer/47dc55d9d9e22b8253f157baf2116865 to your computer and use it in GitHub Desktop.
Save zhammer/47dc55d9d9e22b8253f157baf2116865 to your computer and use it in GitHub Desktop.
import { useState } from 'react';
type FocusProps = {
autoFocus: boolean;
onBlur: () => void;
onFocus: () => void;
};
/**
* Hook that provides props to focus an element on mount.
*
* ```
* const focusProps = useFocusOnMount();
* return <input {...focusProps} />
* ```
*/
export default function useFocusOnMount(): FocusProps {
const [focused, setFocused] = useState(true);
function onBlur() {
setFocused(false);
}
function onFocus() {
setFocused(true);
}
return {
autoFocus: focused,
onBlur,
onFocus
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment