← Back
react typescript useref

React, drop down menus and references

I've had to implement a dropdown menu. The menu should be closed when clicking outside, so I had to check if the window receives a click and that click is outside the menu itself.

This is done in html using the contains method of the node element. To access the element we use useRef method in react, annotated with the type of the element.

But it seems that the target of the MouseElement doesn't work as node, so we have to force it:

const buttonRef = useRef<HTMLButtonElement>(null);
const menuRef = useRef<HTMLDivElement>(null);
const [isOpen, setOpen] = useState(false);

const toggle = () => setOpen(!isOpen);

function handleClickOutside(event: MouseEvent) {
if (buttonRef.current && !buttonRef.current.contains(event.target as Node)) {
setOpen(false);
} else {
console.log("Clicked inside!");
}
}

useEffect(() => {
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, [handleClickOutside]);

Sources: