Skip to content

Instantly share code, notes, and snippets.

@uniphil
Last active September 20, 2016 03:42
Show Gist options
  • Save uniphil/c490ab2e1b9e624fbb1ad556c5b87e2c to your computer and use it in GitHub Desktop.
Save uniphil/c490ab2e1b9e624fbb1ad556c5b87e2c to your computer and use it in GitHub Desktop.
React CSS API sketch
import React from 'react';
import css from 'blahcss';
const BlahSFC = ({ title }) => css((
<div>
<header>
<h1>{title}</h1>
<p>some text in the header</p>
</header>
<section>
<p>the section stuff</p>
<p><a href="#">fer real</a></p>
</section>
</div>
), {
p: {
lineHeight: '1.4',
}
header: {
padding: '3em',
p: {
fontSize: '1.2em',
},
},
section: {
padding: '1em',
a: {
textDecoration: 'none',
':hover' {
background: 'yellow',
},
},
},
});
class BlahComponent extends React.Component {
render() {
const { size } = this.props;
return css((
<div>
im a square
</div>
), {
div: {
backround: 'dodgerblue',
height: `${size}px`,
width: `${size}px`,
}
});
}
}
import React from 'react';
const apply = (jsx, rules) =>
jsx.type in rules
? {
elementStyle: Object
.keys(rules[jsx.type])
.filter(k =>
typeof rules[jsx.type][k] === 'string')
.reduce((acc, k) => {
acc[k] = rules[jsx.type][k]
return acc;
}, {}),
childRules: Object.assign(rules, Object
.keys(rules[jsx.type])
.filter(k =>
typeof rules[jsx.type][k] === 'object')
.reduce((acc, k) => {
acc[k] = rules[k]
? Object.assign(rules[k], rules[jsx.type][k])
: rules[jsx.type][k];
return acc;
}, {})),
}
: {
elementStyle: {},
childRules: rules,
};
const css = (jsx, rules) => {
const props = jsx.props;
const { elementStyle, childRules } = apply(jsx, rules);
return Object.assign({}, jsx, {
props: Object.assign({}, props, {
children: Array.isArray(props.children)
? props.children
.map(child => typeof child.type === 'string'
? css(child, childRules)
: child)
: props.children && typeof props.children.type === 'string'
? css(props.children, childRules)
: props.children,
style: props.style
? Object.assign(elementStyle, props.style)
: elementStyle,
}),
});
return jsx;
};
const TestSFC = ({ stop }) => css((
<div>
<p>hello</p>
</div>
), {
div: {
background: 'dodgerblue',
padding: '1em',
p: {
color: 'white',
fontWeight: 'bold',
},
},
p: {
background: 'tomato',
}
})
export default TestSFC;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment