Comparing The Top Zero-Runtime CSS-in-JS Libraries

Check out the top zero-runtime CSS-in-JS libraries. Learn about their benefits to improve your styling and simplify your writing process.

Many web developers search for a repository on GitHub to contribute to. When they find an exciting project and start contributing, one common challenge they face is locating where the style of a particular component is defined, especially in a larger project.

Fortunately, there’s a simple solution: web developers should define the components and styles in the same file. We can use the CSS-in-JS syntax technique to write components and styles in the same file without much complexity.

According to styled-components creator Max Stoiber, more than 60 percent of React installs also install a CSS-in-JS library. Writing CSS in JS is extremely popular, especially when using a JS framework like React or Angular. Many libraries are available to simplify your process of writing CSS-in-JS.

The Original Article can be found on https://blog.logrocket.com

What is CSS-in-JS?

So, what exactly is CSS-in-JS? It’s a styling technique where JavaScript is used to style the component. We use variables to define the CSS of the component. The variable will contain all the CSS properties, and the content will be wrapped within the component, so it will also have all the defined CSS properties.

The usage of CSS-in-JS has increased in recent times as component-based styling has become more popular. Also, most of the modern JavaScript frameworks are component-based, which fueled the use of CSS-in-JS. Due to this, CSS has now become a module of JavaScript that can be defined and used whenever necessary.

In a modern framework like React, you can use the inline technique to write CSS in the JSX section of your .js file for writing CSS-in-JS. But this technique can be confusing, less readable, and can break the flow of code. It cannot replace the modularity of CSS while writing CSS-in-JS through libraries.

Using CSS-in-JS

When we use CSS-in-JS, we define styling in a variable, which we can use to style the components by wrapping them within the variable tag.

The styled tag is imported from the library. It creates a React component with some styles already defined. It is followed by the HTML tag name that you want to use it — in the example below, we use h1. The h1 tag will be customized according to the defined CSS properties. After coding this, we then define the properties, like so:

const Title = styled.h1`
  font-family: sans-serif;
  font-size: 48px;
  color: #f15f79;
`;

Next, we wrap content within the variable tag.

const App = () => {
     return(
          <Title>
               Hello world!
          </Title>         
)
;

Viola! This is how you define the styles in most of the CSS-in-JS libraries. Now that we’ve covered the basics, let’s look at some advantages of using CSS-in-JS.

Advantages of using CSS-in-JS

  • Easy code sharing: sharing code will become easier and more efficient, as others can easily understand the code instead of trying to find components and styles within the project
  • Less load on the DOM: because we define CSS and components in the same file, the CSS for the component will load only when the component loads, reducing the unnecessary load on the virtual DOM
  • Using JavaScript in CSS: the CSS is defined within the JavaScript file, meaning that we can use complex JavaScript logic to define the value of properties of CSS
  • Better error handling in CSS: because the CSS also undergoes the compiling process, we will receive error messages as it does so, making it easy to find and solve bugs within CSS
  • Portability: having style and components in the same file makes it easy to use the component in other projects

Disadvantages of using CSS-in-JS

There are a few downsides to using CSS-in-JS. A few of them are:

  • Because styling is defined in the .js file, it will affect the styling of the component if JavaScript is disabled
  • Styles are double-parsed, once by the library and then by the browser when styles are inserted
  • Traditionally, when we load a webpage, a browser just reads CSS and applies it. When using CSS-in-JS, the browser dynamically generates a CSS style tag, then reads and applies it to the webpage. Reading and generating this costs performance time

Using zero-runtime CSS-in-JS

One of the solutions to improving lost performance time due to double parsing is that the libraries should convert the CSS-in-JS block into a separate .css file first. Then, the browser will read and apply those styles to the webpage, ultimately saving runtime that’s typically wasted while generating a style tag. This is called zero-runtime CSS-in-JS. It is particularly useful for scaled or complex projects where performance is key.

Zero-runtime means you author your style in a CSS-in-JS syntax, but what is produced is CSS, like any other preprocessor would do.

_– _CSS-Tricks

To achieve zero-runtime CSS-in-JS, there are various libraries you can make use of. Here are some popular ones to consider.

Linaria

Linaria Syntax Logo On A Pink Background

Linaria is the most popular zero-runtime library, and it is written in TypeScript. It has more than 7.1K GitHub stars and 260 GitHub forks. It’s my personal favorite to use because it has easy-to-use syntax and is compatible with almost every modern framework. Linaria converts the CSS-in-JS into a separate .css file while creating the build for production.

It offers many features, including the following:

  • Dynamic prop-based style: you can use a prop to define the value of CSS properties
  • CSS SourceMap: in large projects, it can be difficult to find where the style is defined for the component. If the CSS SourceMap is defined true while writing CSS, it will show the source of the class name of generated CSS in dev tools
  • Linting CSSstylelint will help you to avoid any CSS errors and enforce conventions in your styles
  • JavaScript for logic: you can use JavaScript logic while writing CSS

Here’s how to install it on your machine.

npm install @linaria/core @linaria/react @linaria/babel-preset @linaria/shaker
import { css } from '@linaria/core';
import { modularScale, hiDPI } from 'polished';
import fonts from './fonts';

// Write your styles in `css` tag
const header = css`
  text-transform: uppercase;
  font-family: ${fonts.heading};
  font-size: ${modularScale(2)};

  ${hiDPI(1.5)} {
    font-size: ${modularScale(2.5)};
  }
`;

// Then use it as a class name
<h1 className={header}>Hello world</h1>;

Disadvantages of using Linaria

  • Hard to implement: implementing Linaria properly can be confusing, as it requires setting up Babel
  • Setting up the bundler: to extract CSS from a JS file will require using a bundler, such as Rollup or webpack, which can be difficult to set up
  • Plugin Support: Linaria doesn’t offer quality plugin support for Rust

Astroturf

Astroturf Written On A Brown Card With A Green Background

Astroturf is developed by 4Catalyzer and has more than 2,000 stars on GitHub. It’s a great alternative to Linaria. Astroturf helps you achieve zero runtime by keeping CSS fully static with no runtime parsing. You can write CSS-in-JS in multiple ways through Astroturf’s scoped stylesheet, React, and by using props and component variants. You can see the implementation here.

The key features include:

  • Flexibility: some frameworks only work with certain CSS processing, but Astroturf is flexible and is compatible with most frameworks
  • Props support: it supports props features of React to style component according to props
  • Use your existing tools: you can use Sass and PostCSS to write style definitions in the JavaScript

Here’s how to get started.

npm i astroturf
import React from "react";
import { css } from "astroturf";
const btn = css`
  color: black;
  border: 1px solid black;
  background-color: white;
`;
export default function Button({ children }) {
  return <button className={btn}>{children}</button>;
}

Disadvantages of Astroturf

  • Poor documentation: it lacks a proper readme on GitHub. It also lacks contribution guidelines, and the documentation is short, often leaving out important details
  • Implementation: for extracting styles, Astroturf requires bundling a CSS parser such as rollup or webpack, which can be difficult to implement

Reshadow

Reshadow Website

Reshadow, developed by Artur Kenzhaev, has 340+ stars on GitHub. It is written in JavaScript and provides many features, such as shadow DOM developer experience for virtual DOM-like React, and one of them is writing CSS-in-JS.

Reshadow offers the following perks:

  • The benefit of PostCSS: you will have all the benefits of PostCSS to automate routine CSS operations
  • Static styles: Reshadow offers a static styles extracting option by extracting all your CSS-in-JS into a single .css file
  • CSS module: you can use a CSS module to define the CSS, just as we do in JavaScript

Here’s the installation:

npm install --save reshadow
import {css} from 'reshadow'

const styles = css`
    button {
        font-size: 16px;
        cursor: pointer;
        padding: 10px 15px;
        border-radius: 20px;
        border: 2px solid;
        background-color: white;
        color: darkorange;
    }
`

const Button = ({children, ...props}) => styled(styles)(
    <button {...props}>
        {children}
    </button>,
);

Disadvantages of Reshadow

  • Poor documentation and content: there’s very little content on the web regarding Reshadow, and the docs aren’t incredibly thorough, so learning Reshadow takes time and can be difficult
  • Fewer contributors: there are very few contributors to Reshadow, which hampers the process of solving issues that are attached to the GitHub repository

Conclusion

Zero-runtime CSS-in-JS offers many benefits, especially when developers are contributing to multiple and large projects. The future of CSS-in-JS is pretty bright, especially when it comes to web development and modern frameworks. I hope you will add one of these libraries when you initiate your next project.

#css #javascript #web-development

Comparing The Top Zero-Runtime CSS-in-JS Libraries
10.10 GEEK