Last active
March 6, 2017 16:06
-
-
Save rafaelrinaldi/f56acea9cc09b626d69d69645261601e to your computer and use it in GitHub Desktop.
Handy component base class for CSS in JS projects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** @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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Shout out to the Hyper team for the inspiration.