0

i am learning react+typescript. i want to implement a control like fluentui dropdown:

enter image description here

basically I draw a div and set its position 'relative' then use absolute layout on the dropdown panel. but there is a problem:

how to dismiss the dropdown when click outside area?

Can you share good practices?

萧逸清
  • 165
  • 3
  • 11

1 Answers1

2

Let's assume dropdown is dom node of your dropdown area and dismissDropdown function to dismiss it. Then your code could look like this:

window.addEventListener("click", function (e) {
    // if outside of dropdown
    if (!dropdown.contains(e.target)) {
        dismissDropdown()
    }
});

contains: https://developer.mozilla.org/en-US/docs/Web/API/Node/contains

Basically we check if element on which user clicked is inside dropdown or dropdown itself, and if not then dismiss it.

valerii15298
  • 737
  • 4
  • 15