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:
var inlineStyles = {backgroundColor: 'red', fontSize: 20};
var reactNodeLi = React.createElement('div',{style: inlineStyles}, 'styled')
ReactDOM.render(reactNodeLi, document.getElementById('app1'));
The resulting HTML will look like so:
<div id="app1">
<div style="background-color: red;font-size: 20px;" data-reactid=".0">styled</div>
</div>
Note two things in the JavaScript code above:
- I didn’t have to add the “px” to the
fontSize
value because React did it for me. - When writing CSS properties in JavaScript you have to use the camelCased version of the CSS property (e.g.,
backgroundColor
notbackground-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:
columnCount fillOpacity flex flexGrow flexShrink fontWeight
lineClamp lineHeight opacity order orphans strokeOpacity
widows zIndex zoom