In the next lecture at about 2:32 in the video, an important fix is shown to resolve an issue caused by the changes React v17 makes to events.
Many students have been skipping or missing this fix, so I will share it here as well:
if (ref.current.contains(event.target)) {
should be:
if (ref.current && ref.current.contains(event.target)) {
Here is the full useEffect Hook code from the "Making Use of useRef" lecture:
useEffect(() => {
document.body.addEventListener('click', (event) => {
if (ref.current && ref.current.contains(event.target)) {
return;
}
setOpen(false);
});
}, []);
Here is the full useEffect Hook code from the refactor in the "Body Event Listener Cleanup" lecture:
useEffect(() => {
const onBodyClick = (event) => {
if (ref.current && ref.current.contains(event.target)) {
return;
}
setOpen(false);
};
document.body.addEventListener('click', onBodyClick);
return () => {
document.body.removeEventListener('click', onBodyClick);
};
}, []);