Using Inline CSS in JSX

In order to define inline styles on React nodes you need to pass the style prop/attribute a JavaScript object or reference to an object containing CSS properties and values.

In the code below I first setup a JavaScript object, named styles, containing inline styles. Then I use the { } brackets to reference the object that should be used for the value of the style prop/attribute (e.g., style={styles}).

source code

Notice that, the CSS properties are in a camelCased form similar to what is used when writing CSS properties in JavaScript. This is required because JavaScript does not allow hyphens in names.

When the above React/JSX code is transformed by Babel, and then parsed by a JavaScript engine, the resulting HTML will be:

  1. <div style="color:red;background-color:black;font-weight:bold;" data-reactid=".0">test</div>

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 suprise 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 lineClamp lineHeight
  2. opacity order orphans strokeOpacity widows zIndex zoom