634

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.

eye_mew
  • 8,855
  • 7
  • 30
  • 50
  • 8
    Consider using https://github.com/css-modules/css-modules. https://github.com/gajus/react-css-modules is a React implementation (that I am the author of). CSS Modules and React CSS Modules automatically maps your component class names to CSS modules that are assigned a unique name in the document scope. – Gajus Aug 26 '15 at 10:32
  • 1
    I use CSS while having to write media queries. I also use classes from a base CSS library like bootstrap. – vijayst Aug 20 '16 at 05:44
  • You can use [react-theme](https://github.com/azazdeaz/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](http://material-ui.com/#/customization/themes). – mantramantramantra Jul 08 '15 at 09:56
  • Using the style attribute as the primary means of styling elements is generally not recommended. (https://reactjs.org/docs/dom-elements.html#style) – Omid Ebrahimi May 05 '19 at 08:06
  • As of today, I recommend using a css-in-js solution. It has all the advantages of the style attribute, without the drawbacks. I wrote an answer https://stackoverflow.com/questions/26882177/react-js-inline-style-best-practices/56721113#56721113 – Ben Carp Jun 23 '19 at 08:42

20 Answers20

510

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
<li 
 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'
 style={Object.assign({},
         item.due && styles.due,
         item.due && this.props.dueStyles)}>

Layout

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
<UserBadge
 className="col-xs-12 col-sm-6 col-md-8"
 firstName="Michael"
 lastName="Chan" />

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

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

Appearance

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:

React.createClass({
  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

sleske
  • 81,358
  • 34
  • 189
  • 227
chantastic
  • 10,519
  • 4
  • 25
  • 20
  • 13
    Great read. Also really appreciated [this relevant talk](https://www.youtube.com/watch?v=ERB1TJBn32c) by you, @chantastic. #accepted – eye_mew Aug 03 '15 at 12:24
  • 6
    "Wrap your components with layout components": So obvious, but exactly what I needed. – tandrewnichols Aug 22 '16 at 19:20
  • 2
    @chantastic great answer. A year on, is it all still true? Only really just getting into React and the idea of inline styling, and just wondered if anything has changed since you posted this answer. – alexrussell Sep 02 '16 at 13:51
  • 5
    @alexrussell thanks! i think that the answer here still holds up pretty well. the one area that has changed is that Aphrodite seems to be the community-preferred inline-stiles library (over Radium)—though it's really a matter of personal preference. – chantastic Sep 02 '16 at 16:23
  • 2
    @alexrussell oops. accidentally submitted early. I now us this component technique to style my components. the idea is pretty simple. you create components that are only concerned with the application of style and compose with those, instead of `div`, `span`, `a`, etc. it will help keep style isolated regardless of which library you use. http://reactpatterns.com/#Style component – chantastic Sep 02 '16 at 16:26
  • 2
    Optimizing browser rendering, ie improving performance for mobile devices requires keeping the amount of elements in a page to under 800. Reactjs already requires you to provide a wrapper div for every component. By that nature it is already flawed. Applying oocss like classes ie a grid class onto a div to wrap your component exacerbates that problem. Bottom line: Don't use react. Definately don't use inline styling. – Steve Tomlin Nov 03 '16 at 06:55
  • @chantastic I'm learning react, and tried the approach you suggested but the below doesn't seem to work (added in jsx inside render, it requires to be className), or how should I do it? `
    – MariangeMarcano Mar 17 '17 at 09:31
  • @MariangeMarcano my apologies. It should be `className`, not `class`. The answer has been updated. – chantastic Mar 17 '17 at 23:24
  • I'm working on a SPA with a lot of components. What are your views regarding performance for styling using different techniques. Also, would it be wise to have different css files for different components and include those? – Divyanshu Maithani Mar 19 '17 at 05:08
  • @DivyanshuMaithani I take a pragmatic approach to performance. I author in the way I find most productive then modify for pref *when* a problem appears. Perf for inline vs css-in-js, vs css depends on so many specifics. For the apps I'm working on now, I use a css library called [minions](https://chantastic.org/minions.css/), which I talked about at [Nodevember in 2015](https://www.youtube.com/watch?v=0aBv8dsZs84&t). Cheers! – chantastic Mar 20 '17 at 06:08
  • Can you explain how this piece works or give me the term to research - `item : { complete : { textDecoration : 'line-through', }, }`. Seems like a sort of nested style? – wizloc May 22 '17 at 19:09
  • @wizloc it's they don't have to be nested. the illustration is not prescriptive. those nested objects could be flattened into their own vars. – chantastic May 22 '17 at 20:26
  • what about 'styled components', i think replace all that we know just these days. – stackdave Sep 27 '17 at 21:26
  • 1
    My sense is that at least some of the people who think inline styling is better than external sass might not know very much about pixel-perfect, responsive, production-quality layout. There's a big difference between getting something looking roughly decent in an app and getting something looking just right across a variety of browsers and devices and viewport sizes. – Ringo May 24 '18 at 20:13
  • 1
    Any updates for this post for 2018 changes in ReactJs inline-styling trends/best practices? I've seen a lot of people moving to inline-styling and I can't see a best practice yet... – Mendes Jun 03 '18 at 13:02
  • 1
    @Mendes These two products seem to have the most mindshare for the web: https://emotion.sh/ and https://www.styled-components.com/. – chantastic Jun 14 '18 at 04:12
  • 1
    @Mendes My personal favorite is [react-native-web](https://github.com/necolas/react-native-web) but it the API seems tailored toward teams that are making Web and Native apps and want a common styling API for sharing components. – chantastic Jun 14 '18 at 04:14
235

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

Rafa Viotti
  • 9,998
  • 4
  • 42
  • 62
anandharshan
  • 5,817
  • 4
  • 34
  • 33
  • 3
    so how to use media query for the same if i want to use css Classes in the JS file – Pardeep Jain Sep 08 '17 at 06:41
  • @PardeepJain One way is to use [Emotion](https://github.com/emotion-js/emotion) here is a full lecture of it if you're interested from [meet.js summit 2018](https://www.youtube.com/watch?v=OMKvsZCyYD8&list=PLMCOR-t1TNtdCdasfBpCznQzjttRgYi69&index=10) – Bruno Finger Nov 23 '18 at 12:46
  • 4
    One downside of this approach is that defining styles inline creates a new object each time. This creates a diff in the `style` prop which could lead to performance issues. At the least, define a constant style like this outside of your `render`. Hope this helps! – Dawson B Aug 29 '19 at 10:49
  • How I wish that every answer could be this easy and intuitive to learn. – maverickpuss Feb 25 '21 at 10:21
51

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

Kyle Mathews
  • 3,240
  • 24
  • 22
  • 5
    How will I go about making responsive layouts with inline styles? You don't have the option for media queries here. – Zeus May 10 '17 at 16:49
  • You get the power of js, js can detect browser sizes to dynamically build styles. – JordyvD Aug 11 '17 at 14:53
  • 3
    @g3mini that's not a recommended approach now, anyways, since there are much more powerful solutions for styling components like `CSS Modules`, `styled-components` and others. – Denialos Sep 13 '17 at 11:36
  • There's css in js as well =) I prefer using CSS Modules for the moment though. – JordyvD Sep 24 '17 at 16:51
  • One thing that isn't considered here is that it's very easy to see parent and child styles in the same SASS file, whereas if you needed to look at rules in different components, you might have to be opening and closing a lot of files. – Ringo May 24 '18 at 20:10
28

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' }}

Vivek Mehta
  • 734
  • 8
  • 10
27

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.

Brigand
  • 84,529
  • 20
  • 165
  • 173
  • A related idea we had for some time is the ability to isolate specific CSS rules for a React component using gulp and LESS. Kind of like setting a specific className for each component, then add specific CSS for that class inside the component file. This would make a lot of sense. – David Hellsing Nov 12 '14 at 10:38
  • I often use class names in the format of "component-{app}-{componentName}". "{app}" could be the application's name, or "common" for application independent components. e.g. "component-foo-todo-list" for TodoList and "component-common-light-switch-toggle". For packaged components {app} would be the npm name. Is that what you're referring to? – Brigand Nov 12 '14 at 10:44
  • Yea, well the naming convention is one thing, but the main thing would be to add isolated CSS rules into the same component js file. – David Hellsing Nov 12 '14 at 12:51
  • 2
    This is not true. You can definitly apply custom styling to react components. The component just needs to merge its own style object with an object handed from above, which can come from application data. See last slides of https://speakerdeck.com/vjeux/react-css-in-js like mentioned below – Flion May 29 '15 at 09:53
  • Sure, if you component is a single element, but given `` how do you style that from props? Keep in mind that the html structure should remain an implementation detail, or else you lose a lot of the benefit components provide. – Brigand May 29 '15 at 10:23
  • @FakeRainBrigand By offering more props on the component's "API" for those things you want to allow someone to style and handing them off to the relevant part of the HTML? Or by documenting a complex style object that the component will accept that you'll break apart internally? That doesn't require exposing the HTML structure, as you can be semantic about it. – neverfox Dec 06 '15 at 19:24
19

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
Andhi Irawan
  • 456
  • 8
  • 15
alex_1948511
  • 6,073
  • 2
  • 20
  • 21
13

TLDR - Use a css in js solution (such as Emotion or Styled Components), to enjoy the best css and js has to offer

In css or scss files it is difficult to manage dynamic styles. In inline style tags you can't use media queries or pseudo selectors.

Using CSS in JS, you can enjoy the best of both worlds. Css in JS is to CSS kind of what React is to HTML. It allows to write your css as objects or strings in JS code, and to enjoy the power and the tools of the javascript ecosystem.

As of today, there are a few popular well-supported CSS in js-libraries, including Emotion, Styled-Components, and Radium.


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.

Best Practices

Here are a few best practices I recommend:

  1. Use a CSS in JS solution

  2. 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>
   )
}

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

  2. 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>
)
Ben Carp
  • 24,214
  • 9
  • 60
  • 72
9

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.

Andhi Irawan
  • 456
  • 8
  • 15
widged
  • 2,749
  • 21
  • 25
  • This is how I do it. The only down side is that it's two files instead of one. I can live with that. – Sauce Jul 07 '16 at 10:26
9

Here is the boolean based styling in JSX syntax:

style={{display: this.state.isShowing ? "inherit" : "none"}}
Anupam Maurya
  • 1,927
  • 22
  • 26
8

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;
Alireza
  • 100,211
  • 27
  • 269
  • 172
4

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.

VocoJax
  • 1,469
  • 1
  • 13
  • 19
3

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/

Andhi Irawan
  • 456
  • 8
  • 15
0xdabbad00
  • 998
  • 2
  • 11
  • 22
  • 1
    Can you explain little bit more? – Dmitry Manannikov Apr 04 '15 at 19:31
  • 9
    You are referring specifically to the `unsafe-inline` policy. This policy enables restriction of a style element ` – potench Apr 06 '15 at 04:59
  • I believe both ` – 0xdabbad00 Apr 07 '15 at 02:47
  • 1
    @potench that link was really great, possibly worthy of its own answer – eye_mew Apr 13 '15 at 23:30
  • @potench, totally agree with eye_mew. Post that link as an answer. – Sam R. May 12 '15 at 16:52
  • 7
    Unfortunately, @eye_mew and @Sam-Rad - @potench 's answer is not correct. CSP `unsafe-inline` disables all forms of inline styles including on the style attribute. You can programmatically use the style APIs on an element via JS (e.g. `elem.style.color = 'blue';`), but you can't set the style attribute on an element (just like `'unsafe-inline'` in the script-src directive disallows inline script tags, but also `onclick` attributes and friends.) – Alex Sexton Aug 07 '15 at 17:17
  • 2
    There is more information from the Facebook team on how styles are applied with regard to CSP in React v15 https://github.com/facebook/react/issues/5878. Worth a read – Mark Lundin Mar 24 '16 at 23:02
3

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.

dakt
  • 620
  • 1
  • 9
  • 24
3

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.

Guy
  • 12,488
  • 16
  • 79
  • 119
3

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>;
  }
}
Edgar
  • 6,022
  • 8
  • 33
  • 66
3

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.

Edgar
  • 6,022
  • 8
  • 33
  • 66
Praveen Rao Chavan.G
  • 2,772
  • 3
  • 22
  • 33
3

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.
SamsonTheBrave
  • 527
  • 4
  • 10
1

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;
ABHIJEET KHIRE
  • 2,037
  • 17
  • 10
  • Could you please add some more information about *how* and *why* this code provides an answer to OP's question? Thank you! – deHaar Aug 01 '19 at 10:35
0

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.

Shivang Gupta
  • 3,139
  • 1
  • 25
  • 24
0

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>
        )
    }
}
ROHIT CHAUHAN
  • 148
  • 1
  • 10