I’m trying to create a function that will detect any click outside of an element.
JavaScript
x
16
16
1
useEffect(() => {
2
function handleClickOutside(e) {
3
if (
4
!(
5
e.target.className.includes("ft-btn") ||
6
e.target.parentElement.className.includes("ft-btn")
7
)
8
) {
9
setSortOpen(false);
10
setFilterOpen(false);
11
}
12
}
13
14
document.addEventListener("click", handleClickOutside);
15
}, [sortOpen, filterOpen]);
16
The error says:
TypeError: Cannot read property ‘className’ of null
The function works just fine when it only contains one of the conditions.
Is there any problem with my code? I appreciate any kind of help.
Advertisement
Answer
There are cases in which the parent element is null
, and trying to access the className
property of null
would cause the error. According to MDN:
The Node.parentElement read-only property returns the DOM node’s parent Element, or null if the node either has no parent, or its parent isn’t a DOM Element.
You can Element.closest()
to check if a node or it’s parents match a specific selector:
JavaScript
1
16
16
1
useEffect(() => {
2
function handleClickOutside(e) {
3
if (!e.target.closest('.ft-btn')) { // check if element or parents has class
4
setSortOpen(false);
5
setFilterOpen(false);
6
}
7
}
8
9
document.addEventListener('click', handleClickOutside);
10
11
// cleanup
12
return () => {
13
document.removeEventListener('click', handleClickOutside);
14
};
15
}, [sortOpen, filterOpen]);
16