I have made a Sidepanel component in React and have attached a click listener to close the panel when user clicks anywhere outside the Sidepanel component, like so:
function Sidepanel({ isOpen, children }) {
const [isPanelOpen, setPanelOpen] = useState(isOpen);
const hidePanel = () => setPanelOpen(false);
...
useEffect(() => {
document.addEventListener('click', hidePanel);
return () => {
document.removeEventListener('click', hidePanel);
};
});
return (
<aside
className={`side-panel ${isPanelOpen ? 'side-panel--open' : ''}`}
onClick={stopEventPropagation}
>
<div className="side-panel__body">{children}</div>
</aside>
);
}
function stopEventPropagation (e) {
e.stopPropagation(); // <-- DOESN'T SEEM TO WORK
};
export default Sidepanel;
But, this code doesn't work as expected since the panel starts to close on a click even inside the <aside>
element itself. It seemed like e.stopPropagation()
did nothing so I updated the stopEventPropagation
code to:
function stopEventPropagation (e) {
e.nativeEvent && e.nativeEvent.stopPropagation();
};
...which also didn't work. But, when I did this:
function stopEventPropagation (e) {
e.nativeEvent && e.nativeEvent.stopImmediatePropagation(); // <- IT WORKED!
};
...it worked. Weird!
I read some docs about stopImmediatePropagation I found on Google and realised that although it makes the code work, it just doesn't make any sense here. Am I missing something?