Last active
March 14, 2019 15:46
-
-
Save vernonk/19df5ea1bc1116d6693276bf7399c53c to your computer and use it in GitHub Desktop.
Wanting to understand the best practices of hooks. Is this a bad pattern for a custom hook?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect, useRef } from 'react'; | |
// thinking this could be a common 'toggle' hook to abstract | |
// the keybindings for escape, blur and such | |
const useToggle = (isOpen, classes) => { | |
const [open, setOpen] = useState(isOpen); | |
const sectionEl = useRef(null); | |
const classesString = (open) ? | |
`${classes.messageToggle} ${classes.messageToggleOpen}` : | |
`${classes.messageToggle}`; | |
function handleKeyUp(event) { | |
if (event.key === 'Escape') { | |
setOpen(false); | |
} | |
} | |
function handleBlur(event) { | |
if (!(event.relatedTarget && sectionEl.contains(event.relatedTarget))) { | |
setOpen(false); | |
} | |
} | |
function toggleOpen() { | |
setOpen(!open); | |
} | |
useEffect(() => { | |
document.addEventListener('keydown', handleKeyUp); | |
return () => { | |
document.removeEventListener('keydown', handleKeyUp); | |
}; | |
}, []); | |
return { | |
classesString, | |
open, | |
handleBlur, | |
handleKeyUp, | |
toggleOpen, | |
sectionEl, | |
}; | |
}; | |
export default useToggle; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const DrawerBase = ({ children, classes }) => { | |
const { | |
classesString, | |
open, | |
handleBlur, | |
handleKeyUp, | |
sectionEl, | |
toggleOpen, | |
} = useDrawerToggle(false, classes); | |
return ( | |
<section | |
onBlur={handleBlur} | |
ref={sectionEl} | |
> | |
<button | |
onClick={toggleOpen} | |
onKeyUp={handleKeyUp} | |
className={`icon-chat-bubble unread ${classesString}`} | |
/> | |
<Drawer open={open} className={classes.drawer} anchorTo="right"> | |
{children} | |
</Drawer> | |
</section> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment