Sunday, January 18, 2015

Styles in Javascript

Chris Chedeau gave an excellent presentation about using Javascript for styling.

Inspired by Chris' talk, I decided to try it out on one of my side projects, the game of Reversi (Othello) implemented in React.js (demo). React is a good candidate to use Javascript for your styles because it converts Javascript objects to CSS:
render: function() {
    var styles = {
        textAlign: 'center',
        [...]
    };

    return <p style={styles}>{this.props.message}</p>;
}
Let's take a look at what we can do. Out of the box, we have mixins in the form of Javascript functions:
var Player = require('../lib/Player');

function getBackgroundImage(player) {
    if (player === Player.One) return 'url("img/red.png")';
    if (player === Player.Two) return 'url("img/blue.png")';

    return 'none';
}

module.exports = function(player) {
    return {
        backgroundImage: getBackgroundImage(player),
        [...]
    };
};
We can extend styles with this mixin by merging Javascript objects:
var Player = require('../lib/Player');
var extend = require('object-assign');
var cellStyle = require('../styles/cell');

function buildStyles(owner, playerHint) {
    var cellAppearance = (owner !== Player.None)
        ? owner
        : playerHint;

    return extend({
        border: '1px solid black'
    }, cellStyle(cellAppearance));
}
And, of course, we have variables and constants:
module.exports = {
    fontSize: 24
};
Hopefully the advantages to this approach over something like Sass are clear. Since it's Just Javascript, you don't need to learn another language to get the features of a CSS preprocessor.

While I'm not completely convinced, this is a compelling approach to styling your applications, especially if you're already using React.

No comments:

Post a Comment