I’m trying to create a function that will detect any click outside of an element.
useEffect(() => {
function handleClickOutside(e) {
if (
!(
e.target.className.includes("ft-btn") ||
e.target.parentElement.className.includes("ft-btn")
)
) {
setSortOpen(false);
setFilterOpen(false);
}
}
document.addEventListener("click", handleClickOutside);
}, [sortOpen, filterOpen]);
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:
useEffect(() => {
function handleClickOutside(e) {
if (!e.target.closest('.ft-btn')) { // check if element or parents has class
setSortOpen(false);
setFilterOpen(false);
}
}
document.addEventListener('click', handleClickOutside);
// cleanup
return () => {
document.removeEventListener('click', handleClickOutside);
};
}, [sortOpen, filterOpen]);