Last active
August 29, 2015 14:16
-
-
Save mattmccray/d664fa23078c699c0661 to your computer and use it in GitHub Desktop.
React Inline Styles, ES6 Template Strings Processed via LessCSS
This file contains hidden or 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
| /* global less, _ */ | |
| export function componentStyles( context={}, filename='?') { | |
| if( _.isArray( context)) { | |
| return componentStyles()( context) | |
| } | |
| let ctx= _.extend( {}, componentStyles.context, context) | |
| return function ( rules, ...subs){ | |
| let options= { filename, globalVars: ctx, }, | |
| source= _.chain( rules).zip( subs).flatten().value().join('') | |
| less.render( source, options, (err, output)=>{ | |
| if( err) { | |
| throw new Error("Component Style Error:", err) | |
| } | |
| let style= document.createElement( 'style') | |
| style.innerHTML= output.css | |
| document.getElementsByTagName( 'HEAD')[ 0].appendChild( style) | |
| }) | |
| } | |
| } | |
| componentStyles.context= { } | |
| componentStyles.vars= ( context={})=>{ | |
| return _.extend( componentStyles.context, context) | |
| } |
This file contains hidden or 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 {componentStyles} from './componentStyles' | |
| export let MyTest= React.createClass({ | |
| render() { | |
| return <div className="MyTest">Testing</div> | |
| } | |
| }) | |
| // You can set global vars: | |
| componentStyles.vars({ | |
| border_color: 'green' | |
| }) | |
| // You can pass local less vars, and use variable substitution too: | |
| let borderWidth= 2 | |
| componentStyles({ color:'red' })` | |
| .MyTest { | |
| color: @color; | |
| border: ${ borderWidth }px solid @border_color; | |
| } | |
| ` |
Author
Author
Something I'm thinking about adding support for...
import {componentStyles} from './componentStyles'
// Creates a rule with an auto-generated className that you use in your component...
let _styleName= componentStyles`
color: @color;
&.-debug {
outline: 1px solid red;
}
`
export let MyTest= React.createClass({
render() {
return <div className={ _styleName }>Testing</div>
}
})
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If found useful, it'd be pretty easy to remove the underscore dependency.
Really, I'd rather not use the full Less engine but something a lot smaller. The things I'd want/need: Nested rules, variables, auto-prefixing... That's probably it, actually.