Question

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?

Was it helpful?

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 + ".

OTHER TIPS

How about:

format = function(format) {
    var args = Array.prototype.slice.call(arguments, 1);
    return format.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
        ? args[number] 
        : match
      ;
   });
};

Then

<div style={{transform: this.getTransform()}}></div>
[...]
getTransform: function() {
   var s = this.state;
   return format("translate({0}px, {1}px) scale({2}) rotate({3}deg)",
            s.x, s.y, s.scale, s.angle);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top