[css] React.js inline style best practices

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

const MyDiv = React.createClass({
  render: function() {
    const 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.

This question is related to css reactjs inline-styles

The answer is


You can use inline styles but you will have some limitations if you are using them in all of your stylings, some known limitations are you can't use CSS pseudo selectors and media queries in there.

You can use Radium to solve this but still, I feel has the project grows its gonna get cumbersome.

I would recommend using CSS modules.

using CSS Modules you will have the freedom of writing CSS in CSS file and don't have to worry about the naming clashes, it will be taken care by CSS Modules.

An advantage of this method is that it gives you styling functionality to the specific component. This will create much more maintainable code and readable project architecture for the next developer to work on your project.


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.


2020 Update: The best practice is to use a library that has already done the hard work for you and doesn't kill your team when you make the switch as pointed out by the originally accepted answer in this video (it's still relevant). Also just to get a sense on trends this is a very helpful chart. After doing my own research on this I chose to use Emotion for my new projects and it has proven to be very flexible and scaleable.

Given that the most upvoted answer from 2015 recommended Radium which is now relegated to maintenance mode. So it seems reasonable to add a list of alternatives. The post discontinuing Radium suggests a few libraries. Each of the sites linked has examples readily available so I will refrain from copy and pasting the code here.

  • Emotion which is "inspired by" styled-components among others, uses styles in js and can be framework agnostic, but definitely promotes its React library. Emotion has been kept up to date as of this post.
  • styled-components is comparable and offers many of the same features as Emotion. Also actively being maintained. Both Emotion and styled-components have similar syntax. It is built specifically to work with React components.
  • JSS Yet another option for styles in js which is framework agnostic though it does have a number of framework packages, React-JSS among them.

Styling in JSX is very similar to styling in HTML.

HTML Case:

div style="background-color: red; color: white"

JSX Case:

div style={{ backgroundColor: 'red', color: 'white' }}


Anyway inline css is never recommended. We used styled-components in our project which is based on JSS. It protects css overriding by adding dynamic class names on components. You can also add css values based on the props passed.


For some components, it is easier to use inline styles. Also, I find it easier and more concise (as I'm using Javascript and not CSS) to animate component styles.

For stand-alone components, I use the 'Spread Operator' or the '...'. For me, it's clear, beautiful, and works in a tight space. Here is a little loading animation I made to show it's benefits:

<div style={{...this.styles.container, ...this.state.opacity}}>
    <div style={{...this.state.colors[0], ...this.styles.block}}/>
    <div style={{...this.state.colors[1], ...this.styles.block}}/>
    <div style={{...this.state.colors[2], ...this.styles.block}}/>
    <div style={{...this.state.colors[7], ...this.styles.block}}/>
    <div style={{...this.styles.block}}/>
    <div style={{...this.state.colors[3], ...this.styles.block}}/>
    <div style={{...this.state.colors[6], ...this.styles.block}}/>
    <div style={{...this.state.colors[5], ...this.styles.block}}/>
    <div style={{...this.state.colors[4], ...this.styles.block}}/>
  </div>

    this.styles = {
  container: {
    'display': 'flex',
    'flexDirection': 'row',
    'justifyContent': 'center',
    'alignItems': 'center',
    'flexWrap': 'wrap',
    'width': 21,
    'height': 21,
    'borderRadius': '50%'
  },
  block: {
    'width': 7,
    'height': 7,
    'borderRadius': '50%',
  }
}
this.state = {
  colors: [
    { backgroundColor: 'red'},
    { backgroundColor: 'blue'},
    { backgroundColor: 'yellow'},
    { backgroundColor: 'green'},
    { backgroundColor: 'white'},
    { backgroundColor: 'white'},
    { backgroundColor: 'white'},
    { backgroundColor: 'white'},
    { backgroundColor: 'white'},
  ],
  opacity: {
    'opacity': 0
  }
}

EDIT NOVEMBER 2019

Working in the industry (A Fortune 500 company), I am NOT allowed to make any inline styling. In our team, we've decided that inline style are unreadable and not maintainable. And, after having seen first hand how inline styles make supporting an application completely intolerable, I'd have to agree. I completely discourage inline styles.


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.

Update: To explain further, CSP is HTTP headers sent by the server that restrict what content can appear on the page. It is simply 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 is 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/


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.


I prefer to use styled-components. It provide better solution for design.

import React, { Component, Fragment } from 'react'
import styled from 'styled-components';

const StyledDiv = styled.div`
    display: block;
    margin-left: auto;
    margin-right: auto;
    font-size:200; // here we can set static
    color: ${props => props.color} // set dynamic color by props
`;

export default class RenderHtml extends Component {
    render() {
        return (
            <Fragment>
                <StyledDiv color={'white'}>
                    Have a good and productive day!
                </StyledDiv>
            </Fragment>
        )
    }
}

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


Comparing to writing your styles in a CSS file, React's style attribute has the following advantages:

  1. The ability to use the tools javascript as a programming language provides to control the style of your elements. This includes embedding variables, using conditions, and passing styles to a child component.
  2. A "component" approach. No more separation of HTML, JS, and CSS code wrote for the component. Component's code is consolidated and written in one place.

However, the React's style attribute comes with a few drawbacks - you can't

  1. Can't use media queries
  2. Can't use pseudo-selectors,
  3. less efficient compared to CSS classes.

Using CSS in JS, you can get all the advantages of a style tag, without those drawbacks. As of today, there are a few popular well-supported CSS in js-libraries, including Emotion, Styled-Components, and Radium. Those libraries are to CSS kind of what React is to HTML. They allow you to write your CSS and control your CSS in your JS code.

let's compare how our code will look for styling a simple element. We'll style a "hello world" div so it shows big on desktop and smaller on mobile.

Using the style attribute

return (
   <div style={{fontSize:24}} className="hello-world">
      Hello world
   </div>
)

Since media query is not possible in a style tag, we'll have to add a className to the element and add a css rule.

@media screen and (max-width: 700px){
   .hello-world {
      font-size: 16px; 
   }
}

Using Emotion's 10 CSS tag

return (
   <div
      css={{
         fontSize: 24, 
         [CSS_CONSTS.MOBILE_MAX_MEDIA_QUERY]:{
            fontSize: 16 
         }
      }
   >
      Hello world
   </div>
)

Emotion also supports template strings as well as styled-components. So if you prefer you can write:

return (
   <Box>
      Hello world
   </Box>
)

const Box = styled.div`
   font-size: 24px; 
   ${CSS_CONSTS.MOBILE_MAX_MEDIA_QUERY}{
      font-size: 16px; 
   }
`

Behind the hoods "CSS in JS" uses CSS classes. Emotion specifically built with performance in mind and uses caching. Compared to React style attributes CSS in JS will provide better performance.

###Best Practices

Here are a few best practices I recommend:

  1. If you want to style your elements inline, or in your JS, use a CSS-in-js library, don't use a style attribute.

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

  1. If you use a css-in-js solution there is no need to write styles in CSS files. Writing your CSS in JS is superior as you can use all the tools a programming language as JS provides.

should I avoid inline styles completely?

  1. Structuring your style code in JS is pretty similar to structuring your code in general. For example:
  • recognize styles that repeat, and write them in one place. There are two ways to do this in Emotion:
// option 1 - Write common styles in CONSTANT variables
// styles.js
export const COMMON_STYLES = {
   BUTTON: css`
      background-color: blue; 
      color: white; 
      :hover {
         background-color: dark-blue; 
      }
   `
}

// SomeButton.js
const SomeButton = (props) => {
   ...
   return (
      <button
         css={COMMON_STYLES.BUTTON}
         ...
      >
         Click Me
      </button>
   )
}

// Option 2 - Write your common styles in a dedicated component 

const Button = styled.button`
   background-color: blue; 
   color: white; 
   :hover {
      background-color: dark-blue; 
   }   
`

const SomeButton = (props) => {
   ...
   return (
      <Button ...> 
         Click me
      </Button>
   )
}

  • React coding pattern is of encapsulated components - HTML and JS that controls a component is written in one file. That is where your css/style code to style that component belongs.

  • When necessary, add a styling prop to your component. This way you can reuse code and style written in a child component, and customize it to your specific needs by the parent component.

const Button = styled.button([COMMON_STYLES.BUTTON, props=>props.stl])

const SmallButton = (props)=>(
   <Button 
      ...
      stl={css`font-size: 12px`}
   >
      Click me if you can see me
   </Button>
)

const BigButton = (props) => (
   <Button
      ...
      stl={css`font-size: 30px;`}
   >
      Click me
   </Button>
)

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...

I personally mix them depends on my need, for example... Try to use external css, but if needed React will accept style as well, you need to pass it as an object with key value, something like this below:

import React from 'react';

const App = props => {
  return (
    <div className="app" style={{background: 'red', color: 'white'}}>  /*<<<<look at style here*/
      Hello World...
    </div>
  )
}

export default App;

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


You can use StrCSS as well, it creates isolated classnames and much more! Example code would look like. You can (optional) install the VSCode extension from the Visual Studio Marketplace for syntax highlighting support!

source: strcss

import { Sheet } from "strcss";
import React, { Component } from "react";

const sheet = new Sheet(`
  map button
    color green
    color red !ios
    fontSize 16
  on hover
    opacity .5
  at mobile
    fontSize 10
`);

export class User extends Component {
  render() {
    return <div className={sheet.map.button}>
      {"Look mom, I'm green!
      Unless you're on iOS..."}
    </div>;
  }
}

James K Nelson in his letter "Why You Shouldn’t Style React Components With JavaScript" states that there is no actual 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 theses in favor of CSS:

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

Some time we require to style some element from a component but if we have to display that component only ones or the style is so less then instead of using the CSS class we go for the inline style in react js. reactjs inline style is as same as HTML inline style just the property names are a little bit different

Write your style in any tag using style={{prop:"value"}}

import React, { Component } from "react";
    import { Redirect } from "react-router";

    class InlineStyle extends Component {
      constructor(props) {
        super(props);
        this.state = {};
      }

      render() {
        return (
          <div>
            <div>
              <div
                style={{
                  color: "red",
                  fontSize: 40,
                  background: "green"
                }}// this is inline style in reactjs
              >

              </div>
            </div>
          </div>
        );
      }
    }
    export default InlineStyle;

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 lose the critical notion of separating of concern. View vs style. If you share your component, it is easier for others to theme it to match the rest of their web page.


Here is the boolean based styling in JSX syntax:

style={{display: this.state.isShowing ? "inherit" : "none"}}

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.


Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to inline-styles

React.js inline style best practices Using CSS :before and :after pseudo-elements with inline CSS? CSS Pseudo-classes with inline styles How to write a:hover in inline CSS?