Using variables
Once variables have been defined, they can be imported
and used to declare styles with stylex.create.
Assume the following variables have been defined in a file called
tokens.stylex.js:
tokens.stylex.js
import * as stylex from '@stylexjs/stylex';
// A constant can be used to avoid repeating the media query
const DARK = '@media (prefers-color-scheme: dark)';
export const colors = stylex.defineVars({
primaryText: {default: 'black', [DARK]: 'white'},
secondaryText: {default: '#333', [DARK]: '#ccc'},
accent: {default: 'blue', [DARK]: 'lightblue'},
background: {default: 'white', [DARK]: 'black'},
lineColor: {default: 'gray', [DARK]: 'lightgray'},
borderRadius: '4px',
fontFamily: 'system-ui, sans-serif',
fontSize: '16px',
});
These styles can the imported and used like so:
components/MyComponent.js
import * as stylex from '@stylexjs/stylex';
import {colors, spacing} from '../tokens.styles';
const styles = stylex.create({
container: {
color: colors.primaryText,
backgroundColor: colors.background,
padding: spacing.medium,
},
});
Rules when using variables
There are a few rules to keep in mind when using variables:
- Named imports must be used for importing variables.
- Variables must be imported directly from the
.stylex.jsfiles that define them.
tip
Remember that StyleX variables are comprised of CSS identifiers. They cannot be used as values within JavaScript code.