I\'m looking for a way to detect if a click event happened outside of a component, as described in this article. jQuery closest() is used to see if the target from a click e
I had a case when I needed to insert children into the modal conditionally. Something like this, bellow.
const [view, setView] = useState(VIEWS.SomeView)
return (
{VIEWS.Result === view ? (
setView(VIEWS.Details)} />
) : VIEWS.Details === view ? (
setView(VIEWS.Result) /> />
) : null}
)
So !parent.contains(event.target) doesn't work here, because once you detach children, parent (modal) doesn't contain event.target anymore.
The solution I had (which works so far and have no any issue) is to write something like this:
const listener = (event: MouseEvent) => {
if (parentNodeRef && !event.path.includes(parentNodeRef)) callback()
}
If parent contained element from already detached tree, it wouldn't fire callback.
EDIT:
event.path is new and doesn't exit in all browsers yet. Use compoesedPath instead.