Demystifying React Styling Approaches

Suraj KC
YoungInnovations' Blog
6 min readDec 8, 2017

--

ReactJS is revolutionizing the way we develop frontend applications with component based architecture. With all the hype around web components and atomic design for developing modular, and scalable web applications, its an exciting time to be part of react developer community. As a frontend engineer, it is important to transform how we style applications that align well with web components and react design patterns.

One of the first things that we have to decide when starting a react project is the library for styling the application. And trust me it is not going to be easy. The react community has come up with so many libraries with their own set of functionalities and standout features. Through this blog, I would like to share my experiences with couple of styling libraries and concepts that I have extensively used on my projects.

Vanilla CSS

This is the default option that comes up with create-react-app. It is fairly easy to get started and this is how we traditionally style web pages with CSS. We can get by in most projects without overhead of using external styling libraries with just vanilla CSS. This approach is suitable for simple and minimal web applications. We can also extend our CSS with preprocessor like SASS/LESS/Stylus.

//card.jsimport React from 'react';
import 'card.css';
const Card = () => (<div class="card" >
<img class="card-img-top" src="..." alt="Card image cap">
<div class="card-block">
<h4 class="card-title">Card title</h4>
<p class="card-text">Card desc</p>
</div>
</div>
);//card.css.card{
position: relative;
display: flex;
flex-direction: column;
background-color: #fff;
border: 1px solid grey;
border-radius: 4px;
}
.card-img-top{
height: 180px;
width: 100%;
display: block;
}
.card-block{
flex: 1 1 auto;
padding: 18px;
}

The problem with Vanilla CSS

While this approach is fine for small scale projects, styling gets very difficult as the complexity of the project grows. The major issue is the global scope of CSS and I cannot stress this enough. The CSS we are writing is applicable to entire application. It raises specificity and class names collisions, unnecessary selector nesting and difficulty in debugging.

React encompasses web component based architecture. And vanilla CSS does not align well with this standard.

The solution

The react developer community has come up with awesome libraries for styling react components that align well with modern web component standards and at the same time make styling locally scoped to the component.

For quite some time, I have been trying hard to make sense of where CSS fits in this component driven web development. A component should be independent, modular and should follow single responsibility principle. And CSS also should live and breathe independently along with its own component without affecting styling of other parts of the application. So, its always a good idea to avoid global CSS in styling react applications.

Getting started with this new paradigm can be a little complicated at first. Here are some guidelines that can help make you make transition to component based styling pattern in the right direction.

Don’t reuse CSS, reuse component with its CSS

CSS Modules

CSS module is basically css files in which class names are scoped locally by default. CSS module makes CSS classes local for every component declared within by adding hashes in class names which are unique to each component, thus preventing CSS classes from one component overriding or conflicting with CSS in other components.

panel.js

import React from "react";
import style from "./panel.css";
const Panel = () => {return (
<div className={style.panelDefault}>
<div className={style.panelBody}>A Basic Panel</div>
</div>
)
}
export default Panel;

panel.css

.panelDefault {
border-color: #ddd;
}
.panelBody {
padding: 15px;
}

Generated HTML

<div class="panelDefault___3JNN6">
<div class="panelBody___3OqQA">A Basic Panel</div>
</div>

Generated CSS

.panelDefault___3JNN6 {
border-color: #ddd;
}
.panelBody___3OqQA {
padding: 15px;
}

If you are interested to learn more about CSS modules, here is my previous blog on using CSS modules in react applications.

CSS in JS

For a very long time, things were pretty stale and repetitive in the CSS world. When was the last time, you were so very excited to write CSS in your projects with same old CSS layouts,properties and floats over and over again ? While there has been nifty additions like flexbox and some new CSS frameworks, for me, the idea of writing CSS in JavaScript brings the adrenaline rush with new ideas, concepts and endless possibilities.

Inline styles

React is a library for building user interfaces. And a user interface has different states. For example, in a todolist, a lists can be marked as to do, doing, and completed which are its states. These states have to be clearly defined in functionality as well as in style.

Traditionally, we would have different classes for styling different states ie.

.todo--completed{}
.todo--doing{}
.todo--remainig{}

What react does really well is handling states and it is only logical to bring these states back in react and let the library handle the styling as well without overhead of complex mapping of states with class names. React enables us to directly style components without having to learn quirks of complex CSS selectors, inheritance and browser inconsistencies.

const List = () => {var divStyle = {
color: 'white',
backgroundImage: 'url(' + imgUrl + ')',
WebkitTransition: 'all',
msTransition: 'all'
};
return <div style={divStyle}>To do list</div>}//applying conditional inline stylingconst ListItem = (props) => (<li style={props.completed ? 'color' : 'green' : 'red'} />)

If you want to learn more, here is an excellent video about best practices for using inline styling in react.

Extend inline styles with Radium

While inline styles make it seamless and easier to style modular react components, implementing some basic CSS features like media queries and pseudo selectors gets complicated. And we have a small library called Radium to the rescue. Radium is a set of tools that provides powerful styling capabilities in inline styles without using CSS.

import React from 'react';
import Radium from 'radium';
const Button = () => {var styles = {
base: {
color: '#fff',
':hover': {
background: 'red'
},
'@media screen and (min-width: 64em)': {
display: 'none'
},

};
return <button
style={[
styles.base,
styles[this.props.kind]
]}>
{this.props.children}
</button>
}
Button = Radium(Button);

Styled Components

I was skeptical towards this library in favor of CSS modules but I have to admit, it is growing on me and I am kind of favoring this library in my new projects.

Styled components tries to bring state based dynamic styles from inline styling pattern and lets you write CSS in JS without compromises. It also removes the mapping between components and styles which makes code much cleaner. It allows us to explore and unleash the unprecedented capabilities of JavaScript in our CSS code. Missing Sass variables, mixins and functions ? This little library polished is here to help.

Styled component already has an ecosystem of awesome plugins that can significantly improve our styling workflow.

// Create a Title component that'll render an <h1> tag with some styles
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;

// Create a Wrapper component that'll render a <section> tag with some styles
const Wrapper = styled.section`
padding: 4em;
background: papayawhip;
`;

render(
<Wrapper>
<Title>Hello World, this is my first styled component!</Title>
</Wrapper>
);

Conclusion

Phew !! When it comes to react, there are so many choices that can be overwhelming. And the community has not reached consensus about the best library or pattern to style react applications. You can always mix and match the patterns like inline styles with CSS modules or styled components. Or you can always style react components with good old SASS/LESS or just vanilla CSS if its your thing. As for me, I am in between CSS modules and styled components. CSS modules allow code re-usability across projects be it react, angular or plain website. And styling with styled components aligns so well and coordinated with react components and atomic design pattern that I find very intuitive.

Anyways, I would love to hear about how you are styling your react applications. And if I missed anything, do let me know in comments. :)

--

--