Inline Styles

    React includes a built-in way to style your components — all React components that render DOM elements accept a style prop, which sets the style attributes on a DOM element directly. We call these inline styles, just like we do in HTML.

    This is a common and powerful way to style components; it doesn't required any libraries, it works with every platform-specific renderer (web, native, etc), and it can by fully dynamic (computed based on component props).

    Tradeoffs

    Notice how we're able to change the color of our <Card /> component without touching any CSS files or class names. With inline styles, we can leverage JavaScript logic (e.g. variables, merging multiple styles, rendering based on dynamic themes) to style components, without dealing with lots of CSS classnames. For performance, if a style isn't dynamic, we will generally create the style outside of the render function, so that we don't constantly create new objects (which can trigger unnecessary re-renders).

    The main downside of this approach is that we can't use many of the CSS features for dynamic styles — pseudo classes (:hover), media queries, keyframe animations, etc. Some of these features we can emulate relatively easily through JavaScript in our component, but some features such as keyframe animations can't be recreated without a lot of extra effort. Furthermore, if we're relying on external libraries that use CSS for styling, we may have no choice but to add some CSS to our app.

    Another downside is that we don't get vendor prefixing out of the box, although there are several libraries that solve this problem, prefixing our style objects before we pass them into the style attribute of a component.

    In summary:

    Pros

    • Built-in (no libraries/dependencies)
    • Dynamic (variables, themes, merging, etc)
    • Component styles live in the same file as code and behaviors
    • Works on every React renderer (web, native, etc)

    Cons

    • No CSS features (psuedoclasses, media queries, keyframe animations) out of the box
    • No vendor prefixing out of the box
    • New naming scheme / syntax to learn (camel-cased styles, with numbers or strings as values)