I need to specify event
type. Anyone can help with right type exept any, unknown
?
useEffect(() => {
const checkIfClickedOutside = (event: any) => {
if (
isOpened &&
selectRef.current &&
!selectRef.current.contains(event.target)
) {
setIsOpened(false);
}
};
document.addEventListener("mousedown", checkIfClickedOutside);
return () => {
document.removeEventListener("mousedown", checkIfClickedOutside);
};
}, [isOpened]);
CodePudding user response:
You should be able to use the MouseEvent
.
useEffect(() => {
const checkIfClickedOutside = (event: MouseEvent) => {
if (
isOpened &&
selectRef.current &&
!selectRef.current.contains(event.target)
) {
setIsOpened(false);
}
};
document.addEventListener("mousedown", checkIfClickedOutside);
return () => {
document.removeEventListener("mousedown", checkIfClickedOutside);
};
}, [isOpened]);
Do you really need to use mousedown
?
It looks like you want to close a div, when clicking outside. I would suggest, that you use click
instead, as it gives the user the ability to cancel their action by performing the mouseup
outside of the targeted area.