1
0
mirror of https://gitlab.nic.cz/turris/reforis/foris-js.git synced 2024-11-14 17:35:35 +01:00
foris-js/src/utils/hooks.js

37 lines
1.2 KiB
JavaScript
Raw Normal View History

2019-10-07 17:16:27 +02:00
/*
* Copyright (C) 2019 CZ.NIC z.s.p.o. (http://www.nic.cz/)
*
* This is free software, licensed under the GNU General Public License v3.
* See /LICENSE for more information.
*/
import { useState, useEffect } from "react";
/** Execute callback when condition is set to true. */
export function useConditionalTimeout({ callback, timeout = 125 }, ...callbackArgs) {
const [condition, setCondition] = useState(false);
useEffect(() => {
if (condition) {
const interval = setTimeout(() => callback(...callbackArgs), timeout);
return () => setTimeout(interval);
}
}, [condition, callback, timeout, callbackArgs]);
return setCondition;
}
/** Execute callback when user clicks outside specified element. */
export function useClickOutside(element, callback) {
function handleClickOutside(event) {
if (element.current && !element.current.contains(event.target)) {
callback(event);
}
}
useEffect(() => {
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
});
}