Skip to content Skip to sidebar Skip to footer

Litelement - How To Compute Style Based On Property Or Attribute Values

I'm following the LitElement guide here but can't seem to get my custom element's style values calculated based on it's attribute. I want my element to be written in one of followi

Solution 1:

In this code:

staticgetstyles() {
  const background_color = this.darkMode ? css`#000` : css`#fff` ;// ...

styles is a static method, so within it this refers to the MyElement class itself, so this.darkMode is the darkMode property of MyElement and not the darkMode property of any instance of MyElement. Of course, MyElement.darkMode is always undefined, so you always get the "light" styles.

A different and more maintanable approach would be to "reflect" the darkMode property to an attribute of the element with the reflect: true option and then use the CSS attribute selector [dark-mode] to override the "light" styles, e.g.:

.data-container {
  background-color: #fff;
  color: #333;
}
:host([dark-mode]) .data-container {
  background-color: #000;
  color: #fff;
}

You can see this working in the below snippet:

const { LitElement, css, html } = litElement;

classMyElementextendsLitElement {
  staticgetproperties() {
    return {
      data: { type: String },
      darkMode: {
        type: Boolean,
        reflect: true,
      }
    };
  }

  staticgetstyles() {
    return css `
      :host {
        display: block;
      }
      .data-container {
        background-color: #fff;
        color: #333;
      }
      :host([dark-mode]) .data-container {
        background-color: #000;
        color: #fff;
      }
    `;
  }

  constructor() {
    super();
    this.data = "";
    this.darkMode = false;
  }

  render() {
    return html `
      <div class="data-container">
        <p>${this.data}</p>
      </div>
    `;
  }
}

customElements.define('my-element', MyElement);
<scriptsrc="https://bundle.run/lit-element@2.2.1"></script><my-elementdata="some dark values"dark-mode></my-element><my-elementdata="some light values"></my-element>

Post a Comment for "Litelement - How To Compute Style Based On Property Or Attribute Values"