[SalesForce] How to close the dropdown menu in LWC

I found the dropdown menu code in SLDS menu, but the menu doesn't close and stays open. I tried removing the slds-dropdown-trigger, but then it behaves like on hover rather than onClick. I want to know how can i produce the dropdown menu onClick in Lightning Web Component.

Best Answer

You just need to remove the 'slds-is-open' class

template.html

<template>
    <div class="slds-dropdown-trigger slds-dropdown-trigger_click slds-is-open my-menu">
        <button class="slds-button slds-button_icon slds-button_icon-border-filled" aria-haspopup="true" title="Show More">
            <svg class="slds-button__icon" aria-hidden="true">
                <use xlink:href="/assets/icons/utility-sprite/svg/symbols.svg#down"></use>
            </svg>
            <span class="slds-assistive-text">Show More</span>
        </button>
        <div class="slds-dropdown slds-dropdown_left">
            <ul class="slds-dropdown__list" role="menu" aria-label="Show More">
                <li class="slds-dropdown__item" role="presentation">
                    <a href="javascript:void(0);" role="menuitem" tabindex="0">
                        <span class="slds-truncate" title="Menu Item One" onclick={onClick}>Click Me!</span>
                    </a>
                </li>
            </ul>
        </div>
    </div>
</template>

component.js

onClick(){
    this.template.querySelector('.my-menu').classList.remove('slds-is-open');
}

And then you can open the menu again by doing the same in reverse, i.e:

this.template.querySelector('.my-menu').classList.add('slds-is-open');