Skip to main content

Creating themes

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 imported to create a theme like so:

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

// 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',
borderRadius: '4px',
fontFamily: 'system-ui, sans-serif',
fontSize: '16px',
});

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 descendents.

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.