applyCss

How to get applyCss

import { applyCss } from 'fds/system';

Type: Function

Generate a set of attributes that apply the given CSS styles. Styles should use camelCase for property names, and may use nested selectors, media queries etc.

Arguments

# Name Type Description
1. styles Object | Array<Object>

One or multiple object with style rules to apply.

A single object or an array of objects containing style rules to apply to the component.

Eg.

const styles = { maxHeight: '100px' };
...
<Component applyCss={styles}>
...

Note: Use this as a last resort to set certain styles that cannot be modified by other, more explicit props (eg. use <Flex flex="1" /> instead of <Flex applyCss={{ flex: '1' }} />). This helps the framework to reuse more and generate less runtime overhead which in turn helps with (re-)render performance across the board.

Best practices when using applyCss:

  • Separating or grouping style rules. Try to group related style rules that often change together in a single object. Separate unrelated style rules into separate objects. Try to reuse grouped styles when sensible.

  • Static and dynamic styles. Try to define as much of your style rules at the module level. This means they are only processed once by the CSS-in-JS framework. Which gives the best performance.

Styles at the module level are called 'static' styles because they don't (cannot) change during the program's runtime.

You probably also have use cases for styling that depends on component props (and/or other dynamic data in general). These are called 'dynamic' styles because they might change during the program's runtime.

Try to define dynamic styles statically (define your options at the module level): eg. if you have a component that displays either red or green text based on a prop (say, hasError), define two separate style objects at the module level and write a module level function which chooses between the style objects based on its parameters.

If you can't, do not use applyCss: eg. if you have a component that has a height prop to set its height, you cannot define your options at the module level: height has an infinite number of values. Instead just set the style attribute of the element directly using a JSX expression: Eg. <div style={{height: this.props.height }} /> instead of <div {...applyCss({ height: this.props.height })} />.

Returns

Type: Object

A mapping of attribute values by attribute names. Spread this mapping onto an element defined in JSX to apply the given styles to said element. eg. const styles = applyCss({ color: 'blue' }); <div {...styles} />

Was this page helpful?