Skip to main content

Creating themes

Note

The unstable_moduleResolution option needs to be enabled in the StyleX Babel configuration to enable theming APIs.

Once variables have been defined, alternate “themes” can be created to override the values of those variables for specific UI sub-trees.

Creating Themes

Any variable group can be imported to create a theme like so:

themes.js
import * as stylex from '@stylexjs/stylex';
import {colors, spacing} from './tokens.stylex';

// A constant can be used to avoid repeating the media query
const DARK = '@media (prefers-color-scheme: dark)';

// Dracula theme
export const dracula = stylex.createTheme(colors, {
primaryText: {default: 'purple', [DARK]: 'lightpurple'},
secondaryText: {default: 'pink', [DARK]: 'hotpink'},
accent: 'red',
background: {default: '#555', [DARK]: 'black'},
lineColor: 'red',
});

Applying Themes

A “theme” is a style object similar to the ones created with stylex.create(). They can be applied to an element using stylex.props() to override variables for that element and all its descendants.

components/MyComponent.js
import * as stylex from '@stylexjs/stylex';
import {colors, spacing} from '../tokens.styles';
import {dracula} from '../themes';

const styles = stylex.create({
container: {
color: colors.primaryText,
backgroundColor: colors.background,
padding: spacing.medium,
},
});

<div {...stylex.props(dracula, styles.container)}>{children}</div>;

NOTE: All variables in a variable group must be overridden when creating a theme. This choice has been to help catch accidental omissions. Even at the cost of occasional tedium.

Unlike when defining and using variables, themes can be created with stylex.createTheme() anywhere in a codebase, and passed around across files or components.

info

If multiple themes for the same variable group are applied on the same HTML element, the last applied theme wins.