Thursday, April 20, 2017

Quick Tip: How to Style React Components with styled-components

[special]While many aspects of building applications with React have been standardized to some degree, styling is one area where there are still a lot of competing options. Each has its pros can cons, and there is no clear best choice.[/special]

In this article, I will provide a condensed overview of the progression in web application styling with regards to React components. I will also give a brief introduction to styled-components.

Evolution of Styling in JavaScript

The initial release of CSS was in 1996 and not much has changed since. In its 3rd major release and with a 4th on the way, it has continued to grow by adding new features and has maintained its reputation as a fundamental web technology. CSS will always be the gold standard for styling web components but how it's used is changing every day.

From the days when we could build a website from sliced up images to the times when custom hand-rolled CSS could reflect the same as an image, the evolution of CSS implementation has grown with the movement of JavaScript and the web as a platform.

Since React's release in 2013, component-built web applications have become the norm. The implementation of CSS has, in turn, been questioned. The main argument against using CSS in-line with React has been the separation of concerns (SoC). SoC is a design principle that describes the division of a program into sections, each of which addresses a different concern. This principle was used mainly when developers kept the three main web technologies in separate files: styles (CSS), markup (HTML) and logic (JavaScript).

This changed with the introduction of JSX in React. The development team argued that what we had been doing was, in fact, the separation of technologies, not concerns. One could ask, since JSX moved the markup into the JavaScript code, why should the styles be separate?

As opposed to divorcing styles and logic, different approaches can be used to merge them in-line. An example of this can be seen below:

<button style="background: red; border-radius: 8px; color: white;">Click Me</button>

In-line styles move the CSS definitions from the CSS file. This thereby removes the need to import the file and saves on bandwidth, but sacrifices readability, maintainability, and style inheritance.

CSS Modules

button.css

.button {
    background: red;
    border-radius: 8px;
    color: white;
}

button.js

import styles from './button.css';
document.body.innerHTML = `<button class="${styles.button}">test</button>`;

As we can see from the code example above, the CSS still lives in its own file. However, when CSS Modules is bundled with Webpack or another modern bundler, the CSS is added as a script tag to the HTML file. The class names are also hashed to provide a more granular style, resolving the problems that come with cascading style sheets.

The process of hashing involves generating a unique string instead of a class name. Having a class name of "btn" will result in a hash of "DhtEg" which prevents styles cascading and applying styles to unwanted elements.

index.html

<style>
.DhtEg {
    background: red;
    border-radius: 8px;
    color: white;
}
</style>

.....

<button class="DhtEg">test</button>

From the example above we can see the style tag element added by CSS Modules, with the hashed class name and the DOM element we have that uses the hash.

Glamor

Glamor is a CSS-in-JS library that allows us to declare our CSS in the same file as our JavaScript. Glamor, again, hashes the class names but provides a clean syntax to build CSS style sheets via JavaScript.

The style definition is built via a JavaScript variable that describes each of the attributes using camel case syntax. The use of camel case is important as CSS defines all attributes in train case. The main difference is the change of the attribute name. This can be an issue when copying and pasting CSS from other parts of our application or CSS examples. For example overflow-y would be changed to overFlowY. However, with this syntax change Glamor supports media queries and shadow elements giving more power to our styles:

button.js

import { css } from 'glamor';

const rules = css({
    background: red;
    borderRadius: 8px;
    color: 'white';
});

const button = () => {
    return <button {...rules}>Click Me</button>;
};

styled-components

styled-components is a new library that focuses on keeping React components and styles together. Providing a clean and easy to use interface for styling both React and React Native, styled-components is changing not only the implementation but the thought process of building styled React components.

styled-components can be installed from npm via:

npm install styled-components

Imported as any standard npm package:

import styled from 'styled-components';

Once installed it is time to start making styled React components easy and enjoyable.

Building Generic Styled React Components

Styled React components can be built in many ways. The styled-components library provides patterns that enable us to build well-structured UI applications. Building from small UI components, such as buttons, inputs, typography and tabs, creates a more unified and coherent application.

Using our button example from before we can build a generic button using styled-components.

Continue reading %Quick Tip: How to Style React Components with styled-components%


by Chris Laughlin via SitePoint

No comments:

Post a Comment