I have made a dropdown on React Js. I want the dropdown to close when I click outside using onBlur function. The problem here is that it also closes when a dropdown option is clicked, and doesn't execute the function attached to the option. I want to add a condition to the onBlur function which will check if area clicked was inside or outside the dropdown and act accordingly, but I am not sure how to check that.
I tried document.activeElement, but that is selecting the entire body element.
Here is my code Sandbox link: https://codesandbox.io/s/intelligent-tdd-zq4qcr?file=/src/App.js:938-941
This is the function I need help with:
const close = (event) => {
// Help me with this function please
// I need to wrap this function in a condition that checks
// if the click was outside the dropdown
let dropdown = event.target.nextSibling;
// If I comment the lines below,
// it updates the number, but doesn't close the dropdown
if (dropdown?.classList.contains("display")) {
dropdown.classList.remove("display");
setOption("");
}
};
I am adding a class with property display: unset when the dropdown button is clicked. By default, the display is set to none.
EDIT: The number of these dropdown in my original project are variable. They could be two or they could be 10, depending on the user. So I can't maintain it in the state and need to use JavaScript to track which dropdown is clicked.