The What, Why and How of React (Styles)
Tags: webdev, react, javascript
Published: 2018-09-26 00:28:28

---
title: The What, Why and How of React (Styles)
published: true
description: The What, Why and How of React (Styles)
tags: webdev, react, javascript    
---

Hello, this is my third post about the React ecosystem, and today is the turn of one of the most important parts in the development of any FE, `the styles`. Everytime that I have to explain what a frontend developer do in words that even a five years boy or girl can understand, I always start saying that a website as like a human body, the `HTML` could be the bones, the `javascript` can be the brain, and the `CSS` would be the appearance. S0 you need a healthy osseous system, be mentally stable too and obviously, you need the looks good, sound narcissist, but in the end, all the Frontends are little narcissists.

In 2018 we're in a moment when you can do amazing things with javascript, we already have almost 10 years since HTML 5 becomes the final standard for HTML and is hard to find someone who tries to implement an alternative to the style of a website using something different to `CSS`, the style is what makes the difference between an ugly site and a modern one. In this post we're not going to talk about UI/UX, naming conventions or best practices when you try to give the style to your page (or at least not in detail), today we're going to focus on how to include this big world of styling in our React application.

# What's style in React?
React allow you to include CSS in his components in several ways, so you can have 2 approaches when you try to style a React component, each one totally different to the other, basically you can create components where the component can know or handle his own style, or totally agnostic about how they will look, I’m not talking about the `Components vs Containers` struggle, this approach is about the way how we include the style in our React Component, based on that we have these 2 approaches:

+ `SelfStyled Components`(The Cool ones): The component `should include his own definition of whom they should look`, with this the one who consumes the component should not care about defining a style and also you don’t need to have big modules of CSS, just include the style (we will talk about how to make this later) directly in the component, let each one decide.

+ `Pure Components`: These components `don’t know how they should look`, they don’t care, they will use a reference to indicate what component it’s, and trust that doesn't matter where the component is used, some global style will make it looks ok based in that reference, that can be a class name but you don't write any line of CSS.

_NOTE_: For this context the Pure Component term is not the same that the [React API PureComponent](https://reactjs.org/docs/react-api.html#reactpurecomponent).

Both approaches are ok, just depends on what you need. The idea of the first kind of components is that nobody should modify his looks, they own how they should look, no matter who will use it or where the looks are always the same, for the second one, they just don’t care.

Obviously, you can use both approaches, you can have Self Styled components for specific components, like a particular input, DatePicker or Layout; and also have a global style who care about the big picture, resetting some values by default or even selecting the fonts, _IMPORTANT_: If you decide to mix, is extremely important be meticulous in differentiating what you consider global, otherwise you will be fighting on a war that you won't be able to win against the specificity of CSS. If you are going to use CSS, try to follow a name convention, line BEM or whatever like you.


_NOTE:_ If you decide to use Self Styled components don’t try to override specific styles in your global CSS, because you will find yourself writing CSS `solutions` that will finish with a big selector and using `!important` everywhere.
_NOTE 2:_ If you decide to have a global style or any CSS framework like bootstrap, try to follow best practices at the moment of extending styles, sass and less have excellent documentation about how to keep your CSS maintainable.
 
# Why should I care about style in React?
React is a powerful library where we can have a component, who mix the HTML and the js, into one class or function. That class or function handle the render states, how to initialize the component, how to behave after and before a render, an update or an elimination. But is not just business logic, we need to create components who should look ok for what they pretend to do.

So you need to have a way to include the style in your react component, the real question is if I should use a Self Styled component or a Pure Component? You can use both, base on what you really want. I will give some examples of where you should use one or another.

These are the best scenarios to use Pure components:
_I wanna use a CCS framework built (or bought) in our frontend_ If you use something like bootstrap, material UI, or your own CSS framework and you wanna use that in your react application. You need to use a Pure Component approach.
_I wanna keep consistency between all my FEs_ is also a possibility that you have built multiples FE in others frameworks if you don’t wanna worry about defining a CSS framework for each project and usability.

And these are the why for Self Styled components:
_I don’t wanna have a big CSS monolith framework_,  sometimes big monoliths are not the best, one project against other can have particular differences or requirements that can convert our CSS monolith in an awful spaghetti code.
_I wanna use the latest css_, If you want to use the latest features for your sites, you should use this one, because you can be sure of implement what you want in a reduced scope, otherwise, that new CSS feature that works perfectly in your project can create infinite bugs in others projects.

# How implement styles in React
We talk enough about what and why let's go now to the action, I will give simple examples of how to make a Pure Component and a Self Styled Component, let's see:

_Pure Components_
The Pure components, as we said before, don’t have a definition of his style, only a reference to indicate how our component should look and we can use the class name for that, in React we cannot use `class` we should use `className`, in that attribute of our component we can make a reference to any kind of CSS class used for our Application, like this:

```javascript
import { Component } from 'react';

class PureComponent extends Component {
    render() {
    return (
            <div className="container">
                <div className="child" />
            </div>
        );
    }
}

export default (PureComponent);
```
We can see that we have 2 references, one class name called `container` and `child`, for the context of the component, they don’t care about what that means, the definition of the rules for that class is totally independent of the component itself.

But, Where is that style defined? All depends on our architecture, and where’s is running our React Application. I will let you some links to others blogs where you can find specific information about how implement based on what you might have:
_Boostrap_, to allow to use classes like `col-lg-x` or any other bootstrap class you should read this [link](https://react-bootstrap.github.io/getting-started/introduction/)
_Material UI_, to use the [Material UI components](https://material-ui.com/getting-started/usage/)
_Css Loaders to include my own CSS_, if you wanna include your own CSS, you should [read this](https://javascriptplayground.com/css-modules-webpack-react/)

In the most of the cases to use a CSS library what you need to do is include a Link reference, then you should be able to use it just calling the correct class.

_Self Styled Components_
We now are going to talk about the other way to do styling, sometimes what we need is define the specific style for our component, we don’t wanna use any kind of class name or reference to give the styles to our component, what we need is delivery a Component with his logic and style, and we can do it in several ways:

_Including styles with a json_
We can define a JSON, who contains the styles and then injected directly into the component, like this:

```javascript
import { Component } from 'react';

const container = {
    margin: '30px',
    padding: '5px 10px',
    textAlign: 'center'
};

class SelfStyledComponent extends Component {
    render() {
        return (
            <div styles={container}>
                <div style={{color: blue}}/>
            </div>
        );
    }
}

export default (SelfStyledComponent);

```
We need to remember that for properties like `text-align` we should pass that to camel case and use`textAlign` instead.

_Styled Components_
We have a library that allows you to create a Self Styled component in a more friendly way than just injects JSONs, we can use [Styled Components](https://www.styled-components.com/), with this we can include small(or biggest depends on you) parts of SCSS, an assign directly to the React component, like this:

```javascript
import React from 'react';
import styled from 'styled-components';

const Container= styled.div`
    margin: 40px 20px 15px;
    display: flex;
    margin-left: auto;

    div {
        padding: 10px;
        
        &::after {
            backgroung: gray;
        }
    }
`;


const Child = styled.div`
    color: ‘blue’
`;


class SelfStyledComponent extends Component {
    render() {
        return (
                <Container>
                    <Child />
                </Container>
        );
    }
}

export default (SelfStyledComponent);

``` 

With style components you can create custom components taking advance of all the latest features of CSS and SCSS, you can also handle the styles of the components with variables that are very good when you work with themes._

_EDIT September 2018:_
Styled Component is not the only library that allows you to create SelfStyled components how was mention in the comments, there are a lot more repos that will bring you an alternative to do the same. You can check it this [githup repo](https://github.com/MicheleBertoli/css-in-js) written by Michele Bertoli, where you will find a detailed list of libraries to make CSS-in-JS for more information.
 


As you can see, we can have several ways to do the same, the best option depends on you, your technical staff and what do you expect to build. There’s a big number of benefits of each approach, performance, scalability, reusability, and others. Hope this helps you to understand in how to deal with style while you’re developing in React.


#InTheCodeWeTrust