Home » Reactjs » React.js inline style best practices

React.js inline style best practices

Posted by: admin November 29, 2017 Leave a comment


I’m aware that you can specify styles within React classes, like this:

var MyDiv = React.createClass({
  render: function() {
    var style = {
      color: 'white',
      fontSize: 200

    return <div style={style}> Have a good and productive day! </div>;

Should I be aiming to do all styling this way, and have no styles at all specified in my CSS file?

Or should I avoid inline styles completely?

It seems odd and messy to do a little bit of both – two places would need to be checked when tweaking styling.


There aren’t a lot of “Best Practices” yet. Those of us that are using inline-styles, for React components, are still very much experimenting.

There are a number of approaches that vary wildly: React inline-style lib comparison chart

All or nothing?

What we refer to as “style” actually includes quite a few concepts:

  • Layout — how an element/component looks in relationship to others
  • Appearance — the characteristics of an element/component
  • Behavior and state — how an element/component looks in a given state

Start with state-styles

React is already managing the state of your components, this makes styles of state and behavior a natural fit for colocation with your component logic.

Instead of building components to render with conditional state-classes, consider adding state-styles directly:

// Typical component with state-classes
 className={classnames({ 'todo-list__item': true, 'is-complete': item.complete })} />

// Using inline-styles for state
<li className='todo-list__item'
 style={(item.complete) ? styles.complete : {}} />

Note that we’re using a class to style appearance but no longer using any .is- prefixed class for state and behavior.

We can use Object.assign (ES6) or _.extend (underscore/lodash) to add support for multiple states:

// Supporting multiple-states with inline-styles
<li 'todo-list__item'
 style={Object.assign({}, item.complete && styles.complete, item.due && styles.due )}>

Customization and reusability

Now that we’re using Object.assign it becomes very simple to make our component reusable with different styles. If we want to override the default styles, we can do so at the call-site with props, like so: <TodoItem dueStyle={ fontWeight: "bold" } />. Implemented like this:

<li 'todo-list__item'
         item.due && styles.due,
         item.due && this.props.dueStyles)}>


Personally, I don’t see compelling reason to inline layout styles. There are a number of great CSS layout systems out there. I’d just use one.

That said, don’t add layout styles directly to your component. Wrap your components with layout components. Here’s an example.

// This couples your component to the layout system
// It reduces the reusability of your component
 className="col-xs-12 col-sm-6 col-md-8"
 lastName="Chan" />

// This is much easier to maintain and change
<div class="col-xs-12 col-sm-6 col-md-8">
   lastName="Chan" />

For layout support, I often try to design components to be 100% width and height.


This is the most contentious area of the “inline-style” debate. Ultimately, it’s up to the component your designing and the comfort of your team with JavaScript.

One thing is certain, you’ll need the assistance of a library. Browser-states (:hover, :focus), and media-queries are painful in raw React.

I like Radium because the syntax for those hard parts is designed to model that of SASS.

Code organization

Often you’ll see a style object outside of the module. For a todo-list component, it might look something like this:

var styles = {
  root: {
    display: "block"
  item: {
    color: "black"

    complete: {
      textDecoration: "line-through"

    due: {
      color: "red"

getter functions

Adding a bunch of style logic to your template can get a little messy (as seen above). I like to create getter functions to compute styles:

  getStyles: function () {
    return Object.assign(
      item.props.complete && styles.complete,
      item.props.due && styles.due,
      item.props.due && this.props.dueStyles

  render: function () {
    return <li style={this.getStyles()}>{this.props.item}</li>

Further watching

I discussed all of these in more detail at React Europe earlier this year: Inline Styles and when it’s best to ‘just use CSS’.

I’m happy to help as you make new discoveries along the way 🙂 Hit me up -> @chantastic


The style attribute in React expect the value to be an object, ie Key value pair.

style = {} will have another object inside it like {float:’right’} to make it work.

<span style={{float:'right'}}>{'Download Audit'}</span>

Hope this solves the problem


I use inline styles extensively within my React components. I find it so much clearer to colocate styles within components because it’s always clear what styles the component does and doesn’t have. Plus having the full power of Javascript at hand really simplifies more complex styling needs.

I wasn’t convinced at first but after dabbling in it for several months, I’m fully converted and am in process of converting all my CSS to inline or other JS-driven css methods.

This presentation by Facebook employee and React contributor “vjeux” is really helpful as well — https://speakerdeck.com/vjeux/react-css-in-js


The main purpose of the style attribute is for dynamic, state based styles. For example, you could have a width style on a progress bar based on some state, or the position or visibility based on something else.

Styles in JS impose the limitation that the application can’t provide custom styling for a reusable component. This is perfectly acceptable in the aforementioned situations, but not when you change the visible characteristics, especially color.


James K Nelson in his letter “Why You Shouldn’t Style React Components With JavaScript” states that there is no actually need of using inline styles with its downsides. His statement is that old boring css with less/scss is the best solution. The part of his thesises in favor to css:

  • extendable externally
  • leverable (inline styles overleap everything)
  • designer-friendly

What I do is give each one of my reusable component a unique custom element name and then create a css file for that component, specifically, with all styling options for that component (and only for that component).

var MyDiv = React.createClass({
  render: function() {
    return <custom-component style={style}> Have a good and productive day! </custom-component>;

And in file ‘custom-component.css’, every entry will start with the custom-component tag:

custom-component { 
   display: block; /* have it work as a div */
   color: 'white'; 
   fontSize: 200; 
custom-component h1 { 
  font-size: 1.4em; 

That means you don’t loose the critical notion of separating of concern. View vs style. If you share your component, it is easier for other to theme it to match the rest of their web page.


You can use react-theme to organize your inline styles and make them easily customisable when you’re building a reusable component.

It works similar to ThemeManager in material-ui.


I usually have scss file associated to each React component. But, I don’t see reason why you wouldn’t encapsulate the component with logic and look in it. I mean, you have similar thing with web components.


Depending on your configuration inline styling can offer you Hot reload. The webpage is immediately re-rendered every time the style changes. This helps me develop components quicker. Having said that, I am sure you can setup a Hot reload environment for CSS + SCSS.


It’s really depends on how big your application is, if you wanna use bundlers like webpack and bundle CSS and JS together in the build and how you wanna mange your application flow! At the end of day, depends on your situation, you can make decision!

My preference for organising files in big projects are separating CSS and JS files, it could be easier to share, easier for UI people to just go through CSS files, also much neater file organising for the whole application!

Always think this way, make sure in developing phase everything are where they should be, named properly and be easy for other developers to find things…


The problem with inline styles is Content Security Policies (CSP) are becoming more common, which do not allow it. Therefore, I recommend avoiding inline styles completely.

To explain further, CSP are HTTP headers sent by the server that restrict what content can appear on the page. It is simply a further mitigation that can be applied to a server to stop an attacker from doing something naughty if the developer code the site poorly.

The purpose of most of these restrictions is to stop XSS (cross-site scripting) attacks. XSS is where an attacker figures out a way to include his own javascript on your page (for example, if I make my username bob<SCRIPT>alert("hello")</SCRIPT> and then post a comment, and you visit the page, it shouldn’t show an alert). Developers should deny the ability to have a user add content like this to the site, but just in case they made a mistake, then CSP blocks the page from loading if it finds any script> tags.

CSP are just an extra level of protection for developers to ensure if they made a mistake, that an attacker can’t cause problems to visitors to that site.

So that all is XSS, but what if the attacker can’t include <script> tags but can include <style> tags or include a style= parameter on a tag? Then he might be able to change the look of the site in such a way that you’re tricked into clicking the wrong button, or some other problem. This is much less of a concern, but still something to avoid, and CSP does that for you.

A good resource for testing a site for CSP is https://securityheaders.io/

You can read more about CSP at: http://www.html5rocks.com/en/tutorials/security/content-security-policy/