How can I toggle a class in a LitElement Web Component

3.2k views Asked by At

I am working with precompiled stylesheet (from SASS) and only need to toggle classes. I have two elements that will be writing to an event. Based on the event being true/false I want to to toggle a class on my component.

Would this work:

import { LitElement, html } from 'lit-element'
/**
 *
 *
 * @export
 * @class MenuMainButton
 * @extends {LitElement}
 */
export class MenuMainButton extends LitElement {
  static get properties() {
    return {
      name: { type: String },
      toggled: { type: String }
    }
  }

  constructor() {
    super()
    this.name = 'Menu'
    this.toggled = ''
    this.addEventListener('toggle-main-menu', this.handleEvents)
  }

  render() {
    return html`
      <a @click=${this._onClick} class="menu-button wk-app-menu-button app-menu-open ${this.toggled} govuk-body"
        >${this.name}</a
      >
    `
  }

  handleEvents(event) {
    this.toggled = event.toggle ? 'hide-item' : ''
  }

  _onClick() {
    const toggleMainMenu = new CustomEvent('toggle-main-menu', {
      toggle: this.toggled === '' ? 1 : 0
    })
    this.dispatchEvent(toggleMainMenu)
  }
}

window.customElements.define('main-menu-button', MenuMainButton)

1

There are 1 answers

0
JorgeB On

One way to make styles dynamic is to add bindings to the class or style attributes in your template. The lit-html library offers two directives, classMap and styleMap, to conveniently apply classes and styles in HTML templates.

Styles - LitElement