DEV Community

miguel-penaloza
miguel-penaloza

Posted on • Updated on

The What, Why and How of React (Styles)

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.

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:

import { Component } from 'react';

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

export default (PureComponent);
Enter fullscreen mode Exit fullscreen mode

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
Material UI, to use the Material UI components
Css Loaders to include my own CSS, if you wanna include your own CSS, you should read this

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:

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);

Enter fullscreen mode Exit fullscreen mode

We need to remember that for properties like text-align we should pass that to camel case and usetextAlign 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, with this we can include small(or biggest depends on you) parts of SCSS, an assign directly to the React component, like this:

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);

Enter fullscreen mode Exit fullscreen mode

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

Top comments (4)

Collapse
 
equinusocio profile image
Mattia Astorino • Edited

I really don't like styled-components that binds the css to the js. I prefer solutions like css-literal-loader that allows you to extract the literal css and process it as standard css (so you can also use postcss or sass). You write css-in-js, but yout get standard and optimized (and if you want encapsulated) extracted css.

PS: You should mention that styled-components is just one of the many styling possibilities.

Collapse
 
mangel0111 profile image
miguel-penaloza

Hi Mattia,

Thanks for your answer! Yes you're right Styled Components is not the only CSS-in-JS library today, is just the one that I use more, you can check here a list more extended.

About CSS-Literal-loader vs Styled Components, I believe that both are very similar, maybe on the list, we can find a more exact comparison between them, but more important than which one to use, is how to use right, understanding when and why you should SelfStyled components or just Pure Components and rely the definition of the style in another scope.

PS: Thanks again for your comment, I include a note for that!!

Collapse
 
jazkh profile image
jazkh

This is not Pure Component as defined by React doc.
Pure Component is used to avoid re-rendering a component unnecessarily by doing a shallow comparison to check if state has changed. And so it serves a special purpose. You can read more about it on React docs.

This is how you define it.

import React, {PureComponent} from 'react';

class User extends PureComponent {
//some code///
}
Collapse
 
mangel0111 profile image
miguel-penaloza • Edited

Yes, when I say Pure Component was not a reference for the React PureComponent API that's as Base class of React that give you a Component without an implementation of shouldcomponentupdate.

In this case was to mark a difference between a SelfStyled component and non-SelfStyled Components, but you're right I will include a Note indicating that's not the same.

Thanks!