Quick start
Defining styles
Styles are defined using an object syntax and the create()
API.
import * as stylex from '@stylexjs/stylex';
const styles = stylex.create({
root: {
width: '100%',
maxWidth: 800,
minHeight: 40,
},
});
Any number of rules can be created by using additional keys and additional
calls to create()
:
import * as stylex from '@stylexjs/stylex';
const styles = stylex.create({
root: {
width: '100%',
maxWidth: 800,
minHeight: 40,
},
child: {
backgroundColor: 'black',
marginBlock: '1rem',
},
});
const colorStyles = stylex.create({
red: {
backgroundColor: 'lightred',
borderColor: 'darkred',
},
green: {
backgroundColor: 'lightgreen',
borderColor: 'darkgreen',
},
});
Using styles
To use styles they must be passed to the props()
function. Styles can be
combined using an array, and applied conditionally using standard JavaScript
expressions.
import * as React from 'react';
import * as stylex from '@stylexjs/stylex';
const styles = stylex.create({ ... });
function ReactDiv({ color, isActive, style }) {
return <div {...stylex.props(
styles.main,
// apply styles conditionally
isActive && styles.active,
// choose a style variant based on a prop
colorStyles[color]
// styles passed as props
style,
)} />;
}
The example above uses JSX. StyleX itself is framework agnostic. The same code
works with other frameworks that accept className
strings and style
objects
such as SolidJS
, Preact
or Qwik
.
For other frameworks, it's easy to write simple helpers functions to convert the
output of props()
to the appropriate format. For example, here is how you
would use StyleX with an html
template literal in a component built with
Enhance:
- Enhance Component
- Spread helper
import type {StyleXStyles} from '@stylexjs/stylex';
import * as stylex from '@stylexjs/stylex';
import { spread } from './helpers';
const styles = create({ ... });
export default function EnhanceDiv({ html, state }) {
const { attrs } = state;
const { color, isActive = false, style } = state;
// Enhance only accepts string attributes.
const stylesObj = style ? JSON.parse(style) : null;
return html`
<div ${spread(stylex.props(
styles.main,
// apply styles conditionally
isActive && styles.active,
// choose a style variant based on a prop
colorStyles[color],
// styles passed as arguments
stylesObj
))}>
<slot></slot>
</div>
`;
}
helpers.js
const styleStr = (style) =>
Object.entries(style)
.map(([key, value]) => `${key}:${value}`)
.join(';');
export const spread = ({className, style}) =>
`class="${className}" style="${styleStr(style)}"`;