N
N
Nikolay Semenov2017-10-04 07:30:27
JavaScript
Nikolay Semenov, 2017-10-04 07:30:27

How to close dropdown menu in react component?

Guys, hello everyone.
There is such a control with a drop-down context menu

render() {
    return (
      <div className="btn-dwn__wrap marginr-10">
          <button className={"btn-dwn btn--red" + (this.state.dropdownVisible ? ' active' : '')} onClick={this.handleFilterClick.bind(this)}>
            <svg className="icon" viewBox="0 0 100 100">
              <path d="M38.25,50h23.5v31.333L38.25,97V50z M3,3v7.833l35.25,35.25h23.5L97,10.833V3H3z"/>
            </svg>
          </button>
          <div className={"btn-dwn__dropdown" + (this.state.dropdownVisible ? ' active' : '')}></div>
      </div>
    );
  }

there is such a handler
handleFilterClick(event) {
    const target = event.target;
    this.setState(prevState => ({
      dropdownVisible: !prevState.dropdownVisible
    }))
  }

when you click on the filter, the context menu switches to normal. as intended. But how to make it close if the target is not a button and not the menu itself? Tell me pliz

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
davidnum95, 2017-10-04
@nickola105

As an option:

componentDidMount() {
    document.addEventListener('click', this.onClickOutside);
  }

  componentWillUnmount() {
    document.removeEventListener('click', this.onClickOutside);
  }

  onClickOutside = () => {
    this.setState({ visible: false });
  }

S
Sergey Suntsev, 2017-10-04
@GreyCrew

As an option, I can suggest - when opening a modal window, create a component with transparency, width: 100% height: 100% and z-index < modals
and hang a modal window close handler on it when clicked
. For convenience, you can put it in the modal component and just hide the display : none;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question