N
N
nivaech2019-01-16 09:20:45
JavaScript
nivaech, 2019-01-16 09:20:45

How to close the popup when clicking on other menu items (and when clicking on any area outside the window)?

I have a navbar with several menu items that pop up when clicked (a separate hidden component), with a similar function.

onClickMenu1= () => {
        this.setState(({hide1}) => {
            return {
               hide1: !hide1
            }
        });
    }

let classMenu1 = "dropdown-menu1";
    if (hide1) {
          classMenu1 += " visible";
        };

onClickMenu2= () => {
        this.setState(({hide2}) => {
            return {
               hide2: !hide2
            }
        });
    }

let classMenu2 = "dropdown-menu2";
    if (hide2) {
          classMenu2 += " visible";
        };

The pop-up window can be closed if you click on the menu item again, otherwise, when opening other windows, they simply overlap each other. How can I make it so that when one window is opened, others automatically close?
If someone else can suggest how to close the same window by clicking on the area outside the window, I would be grateful.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Antonov, 2019-01-16
@nivaech

componentDidMount() {
        document.addEventListener('click', this.close);
    }
    
    componentWillUnmount() {
        document.removeEventListener('click', this.close);
    }
    
    close = (event) => {
        const domNode = ReactDOM.findDOMNode(this);
        if (!domNode || !domNode.contains(event.target)) {
            this.setState({ isOpened: false });
        }
    }

This is how I do closing something on click anywhere

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question