152
rated 0 times
[
155]
[
3]
/ answers: 1 / hits: 36439
/ 5 Years ago, wed, february 6, 2019, 12:00:00
I am finding that I am reusing behaviour across an app that when a user clicks outside an element I can hide it.
With the introduction of hooks is this something I could put in a hook and share across components to save me writing the same logic in every component?
I have implemented it once in a component as follows.
const Dropdown = () => {
const [isDropdownVisible, setIsDropdownVisible] = useState(false);
const wrapperRef = useRef<HTMLDivElement>(null);
const handleHideDropdown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
setIsDropdownVisible(false);
}
};
const handleClickOutside = (event: Event) => {
if (
wrapperRef.current &&
!wrapperRef.current.contains(event.target as Node)
) {
setIsDropdownVisible(false);
}
};
useEffect(() => {
document.addEventListener('keydown', handleHideDropdown, true);
document.addEventListener('click', handleClickOutside, true);
return () => {
document.removeEventListener('keydown', handleHideDropdown, true);
document.removeEventListener('click', handleClickOutside, true);
};
});
return(
<DropdownWrapper ref={wrapperRef}>
<p>Dropdown</p>
</DropdownWrapper>
);
}
More From » reactjs