Create Styles
The primary utility function is the createStyles function. It makes a call to the css function
from @emotion/css. Emotion still does most of the heavy lifting by handling the serialization,
hashing, caching, and style injection.
Basic Example
In this example, the HTML will look like:
<div class="css-m39zwu"></div>The CSS will look like this:
.css-m39zwu {
background: var(--cnvs-sys-color-bg-default);
color: var(--cnvs-sys-color-fg-inverse);
}Note: The
createStylesfunction handles wrapping our Tokens invar(--tokenName).
We’re using className for simplicity here.
Caution: Performance Hit: Do not inline the call to
createStylesin the render function of a component. This will cause performance issues as a new style is inserted into the browser on every render.
// Bad example (inside render function)
import {PrimaryButton} from '@workday/canvas-kit-react/button';
import {base} from '@workday/canvas-tokens-webs';
function MyComponent() {
const styles = createStyles({color: base.red600}); // Don't do this
return <PrimaryButton className={createStyles({color: base.red600})}>Text</PrimaryButton>;
}When to Use createStyles
createStyles is a great way to generate static styles when styling our components that don’t rely
on dynamic styles. Use createStyles if you want to create re useable styles or need to apply
simple style overrides to our components.
When to Use Something Else
You should use stencils when styling our components that have complex styles and dynamic properties.
Proper Usage
// Bad example (inside render function)
import {base} from '@workday/canvas-tokens-webs';
import {PrimaryButton} from '@workday/canvas-kit-react/button';
function MyComponent() {
const styles = createStyles({color: base.red600}); // Don't do this
return <PrimaryButton cs={styles}>Text</PrimaryButton>;
}
// Good example (outside render function)
import {base} from '@workday/canvas-tokens-webs';
import {PrimaryButton} from '@workday/canvas-kit-react/button';
const styles = createStyles({color: base.red600});
function MyComponent() {
return <PrimaryButton cs={styles}>Text</PrimaryButton>;
}Note: Most of our components support using the
csprop to apply the static styles. It merges everything together and appliesclassNameandstyleattributes to a React element
Performance Benefits
createStyles is performant because:
- Styles are statically evaluated when styles are defined outside the render function
- No new StyleSheets are injected during render
- It works well with the browser’s selector cache