Angular to React | Logo
 

What's the Equivalent of an ng-style Directive in a React Component?

Both React and Angular use a native Javascript object to express inline styles on DOM elements, so the transition from Angular’s directive to the equivalent code inside a React component is about as simple as they come. Keep reading for code samples.

In Angular, ng-style is a quick and easy way to bind style properties on a DOM element to Javascript expressions. You just assign an object to ng-style whose keys correspond to CSS style properties. The values of those keys correspond to the values of the CSS properties on the DOM element. The code sample below makes it easier to understand.

AngularJS Code Sample for ng-style

Start out by defining your style object as a property of your $scope object:

$scope.myStyle = {
  height: '300px',
  width: '250px',
  'background-color': 'aliceBlue'
};

Notice in the code above that background-color is enclosed in quotes. Some CSS property names are not valid Javascript object keys (such as those that are hyphenated). In Angular, when this happens, you need to use quotes to identify the object key. In React, instead of quotes use the camelCased version of the property name. So background-color becomes backgroundColor.

Also take careful notice of the height and width values. They are defined as strings instead of integers, and they’re suffixed with ‘px’. This is a key difference when defining inline styles with Angular versus React. As you’ll see in the example below, React automatically adds the suffix px when appropriate.

Now, to finish out the Angular example, you just need to add the ng-style directive to a DOM element in your view template. It should look something like this:

<div ng-style='myStyle'>
  I have dynamic style properties.
</div>

React Alternative to ng-style

Aside from the differences I mentioned above, the corresponding approach inside a React component is very similar:

var StyleDemoComponent = React.createClass({
  render: function() {
    var myStyle = {
      height: 300,
      width: 250,
      backgroundColor: 'slateBlue'
    };

    return (
      <div style={myStyle}>
        I have dynamic style properties.
      </div>
    );
  }
});

As I mentioned above in the Angular example, React will accept an integer value for some style properties and automatically append px to the value to make it a valid CSS property value. You’ll also notice that I used the camelCased version for backgroundColor instead of the CSS-native property background-color. These are both good things to remember when porting over your Angular directives to React components.

Interested in Writing for Us?

Website developed by Michael Martin  (michael@angulartoreact.com
© 2015-16, All Rights Reserved