Hooks!
January 06, 2020
Some React hooks I recently wrote for a project (ordered alphabetically).
Use Animate Height
useAnimateHeight
will use the Resize Observer API to listen to resize changes within a reffed component, it will then animate its wrapper’s height to adapt to the new height.
const [wrapper, element] = useAnimateHeight()
return (
<div ref={wrapper}>
<div ref={element}>
{/* ... */}
</div>
</div>
)
Use Escape To Close
useEscapeToClose
will listen to escape key presses and call a function once it happens.
function handleClose() {
// closed!
}
useEscapeToClose(handleClose)
Use Focus Trap
useFocusTrap
traps the keyboard focus within a component (the main component). It does so by returning two render functions, these functions should be placed (and called) before the first component and after the last component within the main component.
const [focusTrapStart, focusTrapEnd] = useFocusTrap()
return (
<div>
{focusTrapStart()}
{/* ... */}
{focusTrapEnd()}
</div>
)
Use Is Mobile
useIsMobile
will return true if the user is browsing through a mobile and false otherwise. It will do so by measuring the screen’s width.
const isMobile = useIsMobile()
Use Keyboard Shortcut
useKeyboardShortcut
accepts an object, where the keys are single characters and the values are methods that should be called when the user presses the ctrl key + the character for the method.
function showCommandPalette() {
// called when user presses ctrl+p
}
useKeyboardShortcut({
p: showCommandPalette,
})
Use Maintain Ratio
useMaintainRatio
accepts a number (the ratio) and options (active: boolean; change: ‘width’ | ‘height’) and returns a ref. The component attached to that ref will maintain that aspect ratio by changing its width or height.
const ref = useMaintainRatio(16 / 9, {
change: 'height',
});
return (
<div ref={ref}>
{/* ... */}
</div>
)
Use Prevent Scroll
usePreventScroll
will prevent scrolling as long as its mounted.
usePreventScroll()
Use Resize Observer
useResizeObserver
wraps the Resize Observer API within a hook.
const [ref, entityDimensions] = useResizeObserver()
useEffect(() => {
if (entityDimensions) {
// change!
}
}, [entityDimensions])
return (
<div ref={ref}>
{/* ... */}
</div>
)
Use Scroll To Top
useScrollToTop
will scroll to the top of the page once mounted.
useScrollToTop()
And that’s it for now.