Skip to content

Commit 4b51f91

Browse files
committed
allow sx prop to accept arrays for style composition
1 parent de7f2ba commit 4b51f91

File tree

3 files changed

+54
-1
lines changed

3 files changed

+54
-1
lines changed

packages/docs/src/pages/sx-prop.mdx

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,36 @@ export default props => (
3434
To read more about how the values are converted and for a reference of supported CSS properties, see the
3535
[`@styled-system/css` docs](https://styled-system.com/css).
3636

37+
## Composition
38+
39+
Styles can be composed by using an array of style objects in the `sx` prop.
40+
This works the same way as [Emotion](https://emotion.sh/docs/composition).
41+
42+
```jsx
43+
import React from 'react'
44+
import { css } from 'theme-ui'
45+
46+
const base {
47+
backgroundColor: 'background',
48+
color: 'primary'
49+
}
50+
51+
const danger = {
52+
color: 'red'
53+
}
54+
55+
export default props => (
56+
<div>
57+
<div sx={base}>This will be the primary color</div>
58+
<div sx={[danger, base]}>
59+
This will be also be primary since the base styles
60+
overwrite the danger styles.
61+
</div>
62+
<div sx={[base, danger]}>This will be red</div>
63+
</div>
64+
)
65+
```
66+
3767
## Margin and Padding
3868

3969
Margin and padding are treated as first-class citizens in Styled System,

packages/theme-ui/src/jsx.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ import css from '@styled-system/css'
33

44
const getCSS = props => theme => {
55
if (!props.sx && !props.css) return undefined
6-
const styles = css(props.sx)(theme)
6+
const sx = Array.isArray(props.sx) ? props.sx : [props.sx]
7+
const styles = sx.map(s => css(s)(theme))
78
const raw = typeof props.css === 'function' ? props.css(theme) : props.css
89
return [styles, raw]
910
}

packages/theme-ui/test/jsx.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,28 @@ test('custom pragma adds styles', () => {
2222
expect(json).toHaveStyleRule('background-color', 'tomato')
2323
})
2424

25+
test('accepts array in sx prop', () => {
26+
const json = renderJSON(
27+
jsx('div', {
28+
sx: [
29+
{
30+
mx: 2,
31+
p: 2,
32+
bg: 'tomato',
33+
},
34+
{
35+
mx: 'auto',
36+
position: 'absolute',
37+
},
38+
],
39+
})
40+
)
41+
expect(json).toHaveStyleRule('margin-left', 'auto')
42+
expect(json).toHaveStyleRule('padding', '8px')
43+
expect(json).toHaveStyleRule('background-color', 'tomato')
44+
expect(json).toHaveStyleRule('position', 'absolute')
45+
})
46+
2547
test('adds raw values with css prop', () => {
2648
const json = renderJSON(
2749
jsx('div', {

0 commit comments

Comments
 (0)