Skip to content

[RFC] Use CSS Custom Properties for dynamic styles #595

@giuseppeg

Description

@giuseppeg

The scope of this "RFC" is to discuss about the possibility to use CSS Custom Properties for dynamic styles.

Switching to use CSS Custom Properties might allow us to explore static extraction in the future.

This mode would be optional and disabled by default as many might still need to support IE, it will also be a breaking change because we would need to allow interpolations only for CSS values:

// ✅ <style jsx>{`div { color: ${props.color} }`}</style> // ✅ the expression below must be hoisted <style jsx>{`div { color: ${Math.random() > 0.5 ? 'green' : 'black' } }`}</style> // 🛑 invalid <style jsx>{`div { ${props.color ? `color: ${props.color}` : '' } }`}</style>

How dynamic styles work right now

Interpolations, and therefore the entire template literal containing the CSS, are flagged as dynamic when they have an expression that cannot be evaluated at build time.

When this is the case we rewrite the styles as follow:

<JSXStyle id="123">{`div.__jsx-style-dynamic-selector { color: ${props.color} }`}</JSXStyle>

We also hash the string above to have a base ID, say 123. Then we rewrite the className attribute of every JSX element to include a fn that generates the proper ID at runtime based on props:

<div className={JSXStyle.dynamic([ ['123', [props.color] ])}> <JSXStyle id="123">{`div.__jsx-style-dynamic-selector { color: ${props.color} }`}</JSXStyle> </div>

JSXStyle.dynamic's signature is:

type ClassNames = string // space separated class names type JSXStyleInfo = [BaseID, Array<Props>] type Dynamic = (Array<JSXStyleInfo>) => ClassNames 

It takes an Array<JSXStyleInfo> because there could be multiple style tags per component.

At runtime then it basically maps JSXStyleInfo to create an hash from JSXStyleInfo, and then flattens the result to finally return classnames

jsx-123abc 

Internally then JSXStyle does the same and replaces __jsx-style-dynamic-selector with jsx-123abc.

Proposal

I think that we could rework this part to instead use custom properties:

We won't use any __jsx-style-dynamic-selector but rather use the BaseID to generate the scoped class jsx-123.

Interpolations would be replaced with custom properties:

<JSXStyle id="123">{`div.jsx-123 { color: var(--styled-jsx-123-1) }`}</JSXStyle>

and the root JSXElement would set custom properties using JSXStyle.dynamic:

<div className="jsx-123" style={{ '--styled-jsx-123-1': props.color }}> <JSXStyle id="123">{`div.jsx-123 { color: var(--styled-jsx-123-1) }`}</JSXStyle> </div>

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions