Usage
Set the active theme on the document element and optionally save it to localStorage for persistence across sessions.
import { setTheme } from '@alex.radulescu/styled-static' ;
// Set theme and persist
setTheme ( 'dark' );
// Set theme without persisting (e.g., for preview)
setTheme ( 'pokemon' , false );
Signature
function setTheme (
theme : string ,
persist ?: boolean ,
options ?: { storageKey ?: string ; attribute ?: string }
) : void
Parameters
The theme name to set (e.g., ‘dark’, ‘pokemon’, ‘star-trek’)
Whether to save the theme to localStorage. Set to false for temporary theme changes like previews
Additional configuration options The localStorage key to use for persisting the theme
attribute
string
default: "'data-theme'"
The attribute name to set on documentElement. Supports both data-* attributes and regular attributes
Returns
This function does not return a value
Behavior
The function:
Sets the specified attribute on document.documentElement with the theme value
If persist is true (default), saves the theme to localStorage using the configured storageKey
Handles both data-* attributes and regular attributes correctly
Gracefully handles environments where localStorage is unavailable (e.g., private browsing)
Examples
Switch themes
import { setTheme } from '@alex.radulescu/styled-static' ;
// Switch to dark theme and persist
setTheme ( 'dark' );
// Switch to custom theme and persist
setTheme ( 'pokemon' );
Preview without persisting
// Set theme temporarily for preview
setTheme ( 'pokemon' , false );
Custom storage key and attribute
setTheme ( 'dark' , true , {
storageKey: 'my-app-theme' ,
attribute: 'data-color-mode' ,
});
Using with CSS variables
import { createGlobalStyle , setTheme } from '@alex.radulescu/styled-static' ;
const GlobalStyle = createGlobalStyle `
:root, [data-theme="light"] { --bg: #fff; --text: #1a1a1a; }
[data-theme="dark"] { --bg: #0a0a0a; --text: #f1f5f9; }
[data-theme="pokemon"] { --bg: #ffcb05; --text: #2a75bb; }
` ;
const Card = styled . div `
background: var(--bg);
color: var(--text);
` ;
// Switch between themes
setTheme ( 'dark' );
setTheme ( 'pokemon' , false ); // Preview without persisting