DEV Community

Konnor Rogers
Konnor Rogers

Posted on

1

How to keep a persistent class on a LitElement

When working with lit, sometimes you want the host element to have a persistent class name. A good example is if I were using Shoelace I'd want my elements to look like this:

<sl-button class="sl-button"></sl-button>
Enter fullscreen mode Exit fullscreen mode

That way if a user registers the button under another namespace, they can still target all instances with .sl-button {} in their CSS, or by using querySelectors. There are a number of use-cases, but lets forget about the "why", and focus on the how.

Here is how I found the most effective way to keep a persistent class on a LitElement.

import { LitElement } from "lit"
class MyElement extends LitElement {
  static properties = {
    class: { reflect: true }
  }

  connectedCallback () {
    super.connectedCallback()
    this.classList.add("my-element")
  }

  willUpdate (changedProperties) {
    if (changedProperties.has("class")) {
      this.classList.add("my-element");
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Or for you folks out there using decorators:

import { LitElement } from "lit"
import { property } from "lit/decorators.js"

class MyElement extends LitElement {
  @property({ reflect: true }) class

  connectedCallback () {
    super.connectedCallback()
    this.classList.add("my-element")
  }

  willUpdate (changedProperties) {
    if (changedProperties.has("class")) {
      this.classList.add("my-element");
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

I'm sure there's another way to do this, but this has been the way that's worked for me!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more