Inlining CSS on Element Nodes

To apply inline CSS to a React node you have to pass a style attribute/prop with an object value containing CSS properties and values.

For example, in the code below I am passing a style prop referencing (i.e., inlineStyle) an object containing CSS properties and values:

  1. var inlineStyles = {backgroundColor: 'red', fontSize: 20};
  2. var reactNodeLi = React.createElement('div',{style: inlineStyles}, 'styled')
  3. ReactDOM.render(reactNodeLi, document.getElementById('app1'));

The resulting HTML will look like so:

  1. <div id="app1">
  2. <div style="background-color: red;font-size: 20px;" data-reactid=".0">styled</div>
  3. </div>

Note two things in the JavaScript code above:

  1. I didn’t have to add the “px” to the fontSize value because React did it for me.
  2. When writing CSS properties in JavaScript you have to use the camelCased version of the CSS property (e.g., backgroundColor not background-color).

Notes

  • Vendor prefixes other than ms should begin with a capital letter. This is why WebkitTransition has an uppercase “W”.
  • CamelCased CSS properties shouldn’t be a surprise given this is how it is done when accessing properties on DOM nodes from JS (e.g., document.body.style.backgroundImage)
  • When specifying a pixel value React will automatically append the string “px” for you after your number value except for the following properties:
  1. columnCount fillOpacity flex flexGrow flexShrink fontWeight
  2. lineClamp lineHeight opacity order orphans strokeOpacity
  3. widows zIndex zoom