Skip to content

Instantly share code, notes, and snippets.

@rafaelrinaldi
Last active March 6, 2017 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rafaelrinaldi/f56acea9cc09b626d69d69645261601e to your computer and use it in GitHub Desktop.
Save rafaelrinaldi/f56acea9cc09b626d69d69645261601e to your computer and use it in GitHub Desktop.
Handy component base class for CSS in JS projects
import Preact from 'preact'
import { StyleSheet, css } from 'aphrodite/no-important'
class Component extends Preact.Component {
constructor () {
super()
this._rawStyles = this.styles ? this.styles() : {}
this._styles = StyleSheet.create(this._rawStyles)
this._parseClassNames = this._parseClassNames.bind(this)
}
_parseClassNames (...args) {
const classes = args
// Remove empty rules
.filter(className => (
this._rawStyles[className] &&
Object.keys(this._rawStyles[className]).length
))
.map(className => css(this._styles[className]))
// Remove nulls
.filter(value => Boolean(value))
return classes.length ? classes.join(' ') : null
}
render (props, state) {
if (!this.template) {
return null
}
return this.template({
css: this._parseClassNames,
props,
state
})
}
}
export default Component
/** @jsx h */
import { h } from 'preact'
import Component from './component'
import { container, fontSizes } from '../styles'
class Credits extends Component {
template ({ css, props }) {
const { data } = props
return (
<div className={css('root')}>
<p><strong>Credits</strong></p>
{ data.map(item => <p>{ item }</p>) }
</div>
)
}
styles () {
return {
root: {
...container,
fontSize: fontSizes[6]
}
}
}
}
export default Credits
@rafaelrinaldi
Copy link
Author

Shout out to the Hyper team for the inspiration.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment