I'm using react useEffect hook to create a dropdown component, and added an event listener to close the drop down when the user click out side the drop down, but also have created a button to hide the whole dropdown, in that case the component wouldn't exist after clicking that button so automatically the ref attached to it will equal to null, so I had to clean up by removing the event listener when the drop down is hidden.
The dropdown work well but when I click on the button that hide it it give me an error that says
TypeError: Cannot read property 'contains' of null
I guess the problem is in the clean up function that remove the event listener not working when the user click the button to hide the dropdown entirely, the ref.current was supposed to be cleaned up when the component get hidden because it will be equal to null.
useEffect(() => {
const onBodyClick = (event) => {
if (ref.current.contains(event.target)) {
return;
}
setopen(false);
};
document.body.addEventListener("click", onBodyClick);
return () => {
document.body.removeEventListener("click", onBodyClick);
};
}, []);