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): voidParameters
sheet:CSSStyleSheet: Adopts the new stylesheet object directly.string: Parses the CSS string into a stylesheet, rewrites:hostselectors if Shadow DOM is disabled, and adopts it.null: Detaches and removes the current stylesheet from the element's content root (or document).
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:
- Locate the currently active stylesheet and filter it out of the container's
adoptedStyleSheetsarray. - Convert the new stylesheet parameter into a native
CSSStyleSheetif it is a string. - Apply Light DOM selector rewriting (e.g., converting
:hostto the element's tag name) ifconfig.shadowisfalse. - Append the new stylesheet to
adoptedStyleSheetson either:- The element's
ShadowRoot(if Shadow DOM is enabled). - The
documentor parent Shadow Root (if Shadow DOM is disabled).
- The element's