Search code examples
template-enginereactjs

React.js: Passing values inside attributes


I’m porting the following code from AngularJS to React:

<div style="translate: translate({x}px, {y}px) scale({scale}) rotate({angle}deg)"}></div>

I tried:

<div style="translate: translate({this.state.x}px, {this.state.y}px) scale({this.state.scale}) rotate({this.state.angle}deg)"}></div>

It failed with Parse Error: Line X: Unexpected token }.

The best I came up with is:

<div style={{transform: "translate(" + this.state.x + "px, " + this.state.y + "px) \
    scale(" + this.state.scale + ") \
    rotate(" + this.state.angle + "deg)"}}></div>

That’s a lot of " + this.state.XXX + " and it’s very hard to read.

Is there a better way of doing it?


Solution

  • I came up with AngularJS-style micro-templates function. Usage example:

    <div style={this.evalTpl("translate: translate({{x}}px, {{y}}px) scale({{scale}}) rotate({{angle}}deg)")}></div>
    

    The implementation:

    evalTpl: function(str) {
        var state = this.state;
        return str.replace(/{{.+?}}/g, function(name) {
            name = name.slice(2, -2).trim();
            var value = state[name];
            if (typeof value === 'undefined' || value === null || (!value && isNaN(value))) {
                throw new Error('this.state[' + JSON.stringify(name) + '] is ' + value);
            }
            return value;
        });
    }
    

    It isn’t very good solution overall but, I think, it’s better than " + this.state.XXX + ".