Styling components
Knowledge of component style sheets is required.
Components are styled with the useStyles()
hook (preferred) or the withStyles()
higher-order-component. Both APIs require a
style sheet that is conditionally rendered to CSS to
generate atomic class names.
To continue with the example found in the style sheet documentation, let's design and style a button component. The button file would look something like the following.
- Hook
- HOC
If you're designing components for a library that'll be consumed externally, we suggest exporting the style sheet so that consumers may customize variants.
#
Generating class namesBoth the hook and HOC APIs provide a class name generation function that we aptly name cx
. This
function requires a list of selector names (keys from the style sheet object) in which to render CSS
and apply a class name with, for example.
As demonstrated above, the button
selector will always be rendered. However, the button_selected
and button_disabled
selectors will only be rendered when the button is conditionally updated via
the selected
and disabled
props respectively.
We can take this a step further by supporting
variants. All that's required is to pass an
object as the 1st argument to cx()
with the name of every variant, and the variant to activate.
NOTE: The order of selectors passed to
cx()
does not determine the specificity. The order they are defined in the style sheet does! Be aware of this when developing.
#
Custom class namesYou can pass non-Aesthetic class names to cx()
by passing an array.
#
Alternative stylingBesides the useStyles
hook, there is a special useCss
hook, which is a low-level alternative for
rendering a basic rule object and returning a class name.
Be aware that this hook does not use the component style sheet format and instead uses plain style objects! Because of this, the following features are no longer available:
- Theme object and utility functions
- Structured style blocks
- Variant styles
- Styling multiple elements
- Re-rendering when theme or direction change
- Class name composition
- High-performance and caching
- And other design system related features...