updateStylesheet

While the css tagged template is perfect for fine-grained style changes, there are times when you need to replace or detach stylesheets entirely (e.g., swapping global themes, switching between light and dark mode stylesheets, or handling third-party stylesheets). You can perform these dynamic updates using this.updateStylesheet().

Method Signature

typescript
1updateStylesheet(sheet: CSSStyleSheet | string | null): void

Parameters

Dynamic Theme Swapping Example

In this example, we define two themes and swap the stylesheet dynamically when a user clicks a button:

javascript
1import { WebComponent, html } from '@beforesemicolon/web-component'2 3const lightTheme = `4    :host {5        display: block;6        background-color: white;7        color: black;8        padding: 16px;9    }10`11 12const darkTheme = `13    :host {14        display: block;15        background-color: #222;16        color: white;17        padding: 16px;18    }19`20 21class ThemeBox extends WebComponent {22    initialState = { isDark: false }23    stylesheet = lightTheme24 25    toggleTheme = () => {26        this.setState((prev) => {27            const nextIsDark = !prev.isDark28 29            // Swap stylesheets dynamically30            this.updateStylesheet(nextIsDark ? darkTheme : lightTheme)31 32            return { isDark: nextIsDark }33        })34    }35 36    render() {37        return html`38            <div>39                <p>40                    Current Theme: ${() =>41                        this.state.isDark() ? 'Dark' : 'Light'}42                </p>43                <button onclick="${this.toggleTheme}">Toggle Theme</button>44            </div>45        `46    }47}48 49customElements.define('theme-box', ThemeBox)

Detaching Stylesheets

To remove all styling applied via the component's stylesheet property, call this.updateStylesheet(null):

javascript
1// Remove the current adopted stylesheet2this.updateStylesheet(null)

How WebComponent Handles Swapping

When you call updateStylesheet(sheet), WebComponent will:

  1. Locate the currently active stylesheet and filter it out of the container's adoptedStyleSheets array.
  2. Convert the new stylesheet parameter into a native CSSStyleSheet if it is a string.
  3. Apply Light DOM selector rewriting (e.g., converting :host to the element's tag name) if config.shadow is false.
  4. Append the new stylesheet to adoptedStyleSheets on either:
    • The element's ShadowRoot (if Shadow DOM is enabled).
    • The document or parent Shadow Root (if Shadow DOM is disabled).
edit this doc