Skip to content

Instantly share code, notes, and snippets.

@sseletskyy
Created May 29, 2020 12:40
Show Gist options
  • Save sseletskyy/0269ddee8c4187f7dc3c2f9f40903b8c to your computer and use it in GitHub Desktop.
Save sseletskyy/0269ddee8c4187f7dc3c2f9f40903b8c to your computer and use it in GitHub Desktop.
Custom React Hooks
import { RefObject, useRef } from 'react';
// custom react hook to implement blur logic on click event
// function returns ref and callback
// ref should be set to anchor, e.g. <a ref={ref} ...></a>
// callback should be called without params in onClick handler,
// e.g. <a onClick={(e)=> { forceBlur(); ... } />
export function useForceBlur(): [RefObject<HTMLAnchorElement>, () => void] {
const ref = useRef<HTMLAnchorElement>(null);
const forceBlur = () => {
if (ref?.current?.blur) {
ref.current.blur();
}
};
return [ref, forceBlur];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment