Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 67411

React dropdown that opens a unique div and closes the active one on click

$
0
0

What I want to happen is to show a corresponding div whenever I click on a link. None of the dropdowns should be visible on load. On click, the corresponding div should show and any open ones should close.

So when I click Dropdown1, the div for dropdown1 should show, and close any open divs from other dropdown.

constructor() {
    super();

    this.state = {
        showMenu: false,
    };

    this.showMenu = this.showMenu.bind(this);
    this.closeMenu = this.closeMenu.bind(this);
}

showMenu(event) {
    event.preventDefault();

    this.setState({ showMenu: true }, () => {
        document.addEventListener('click', this.closeMenu);
    });
}

closeMenu(event) {
    if (!this.dropdownMenu.contains(event.target)) {
        this.setState({ showMenu: false}, () => {
            document.removeEventListener('click', this.closeMenu);
        });
    }
}

render() {
    return (
        <div>
            <div onClick={this.showMenu}>Dropdown1</div>
            <div onClick={this.showMenu}>Dropdown2</div>
            <div onClick={this.showMenu}>Dropdown3</div>
            ...
            {/* Dropdown */}                
            {this.state.showMenu ? (
                <div                    
                    ref={(element1) => {
                        this.dropdownMenu = element1;
                    }}
                >
                    <div>
                       ...Dropdown content 1...
                    </div>
                </div>
            ) : null}
            {/* 2nd dropdown here*/}
            {this.state.showMenu ? (
                <div
                    ref={(element2) => {
                        this.dropdownMenu = element2;
                    }}
                >
                    <div>
                        ...Dropdown 2 Content...
                    </div>
                </div>
            ) : null}
           {/* 3rd dropdown here*/}
        </div>
    );
}

Viewing all articles
Browse latest Browse all 67411

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>