2

I have multi-select dropdown, problem is cus when user select one item - dropdown is closed.

How to make that dropdown is closed only on outside click?

Dropdown is made by html ul > li:

// Here we loop trough list of filters and render options as <li> tags
 <ul name="filters" className="dropdown">
    {subFilters.map((filter, i) => (
      <li
        defaultChecked={filter.name}
        onClick={() => handleSelect(filter)}
        className={`option`}>
        <span>{filter.name}</span>
      </li>
    ))}
  </ul>

Css part - Classes used are:

  • dropdown for tag
  • option for
.dropdown {
  display: flex;
  flex-direction: column;
  min-width: 11rem;
  position: absolute;
  z-index: 1;
  font-size: 16px;
  border-radius: 3px;
  border: solid 1px #dee1e5;
  box-shadow: 0 9px 8px rgba(0, 0, 0, 0.05);
  background-color: white;
  outline: none;
  cursor: pointer;
}

.option {
  list-style-type: none;
  padding: 10px 10px 10px 0;
  margin-left: 2.6rem;
}

This is how that dropdown looks: s

Mark James
  • 338
  • 4
  • 15
  • 43
  • https://stackoverflow.com/q/1403615/7203351 please refer this with clear understanding. Don't forget to bind and unbind the clicks – shikhar May 31 '19 at 07:45
  • Possible duplicate of [Use jQuery to hide a DIV when the user clicks outside of it](https://stackoverflow.com/questions/1403615/use-jquery-to-hide-a-div-when-the-user-clicks-outside-of-it) – shikhar May 31 '19 at 07:46
  • 1
    Buddy this is not jquery. – Mark James May 31 '19 at 07:47
  • 1
    maybe [this post from react docs](https://reactjs.org/docs/accessibility.html#mouse-and-pointer-events) can help you – AsukaSong May 31 '19 at 08:22

1 Answers1

3

You can handle this by onBlur event.

Suppose you have snippet like this : <div class="dropdown" onBlur={() => this.handleBlur('myModal')}>Some content</div>

Now this.handleBlur

handleBlur = modalName => {
    this.setState({ [modalName]: false });
};
Meet Zaveri
  • 2,921
  • 1
  • 22
  • 33
  • Didn't help, this handleBlur method what should do? change the state of openedDropdown to false? Not sure to undrestand you function. – Mark James May 31 '19 at 07:48
  • 1
    Suppose modal would have a state which is boolean. So on `true` condition it will be opened and on `false` condition it will be closed. – Meet Zaveri May 31 '19 at 08:45
  • 1
    Eg. Assign state's property to modal's toggle value. Then you have to only update that state's property to open or close modal – Meet Zaveri May 31 '19 at 09:04