Css style

Introduction to CSS-in-JS: Generating CSS from JavaScript

The idea of ​​generating CSS in JavaScript has become more popular over the past few years, largely due to the prevalence of reactive frameworks like React and Slender. Such frameworks do not mandate the use of JavaScript to style components, but they do lend themselves to it. Therefore, a number of CSS-in-JS libraries have been offered to facilitate the process.

This article introduces you to CSS-in-JS, then presents a handful of promising frameworks to implement it.

What is CSS in JavaScript?

Old-school CSS basically has two options: inline definition and loading from an external file. In either case, the browser loads the CSS, parses it, and then applies the styles to the markup. CSS-in-JS offers a third approach: providing CSS by generating it programmatically in code.

The big plus point here is that JavaScript code has full access to variables and conditions, including those representing application state. Therefore, CSS can be created fully responsive to live context. The downside is added complexity. It’s really a compromise because one of the advantages of traditional CSS is simplicity, at least in terms of loading styles.

CSS-in-JS provides syntax to turn your JavaScript into styles that the browser can apply. Whichever framework you use, the result will look something like Listing 1.

Listing 1. CSS-in-JS with the styled-components framework


// Create a Title component that'll render an 

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
tag with some styles const Wrapper = styled.section` padding: 4em; background: papayawhip; `; // Use Title and Wrapper like any other React component – except they're styled! render( Hello World! );

List 1 is taken from stylish component frame. Each framework has its own conventions, but this example gives you the basics of any system:

  1. Define CSS in JavaScript syntax.
  2. Apply styles in markup (like JSX).

Component-level CSS

Large-scale application styles are notoriously prone to bloat. It can be very difficult to understand what influences the characteristics of specific elements in a large layout, and even more difficult to make effective changes. This fragility sometimes makes CSS maintenance a onerous task.

CSS-in-JS solves this problem with component-scoped CSS. Almost all JavaScript frameworks are component-oriented, so generating CSS that is limited to those components is a natural fit.

By automatically ensuring that a component’s styles are applied only to that component, the application developer no longer needs to design globally unique classes to apply across the diversity of pages and layout sections. page. Component-level CSS means that the way a layout is composed naturally informs how CSS styles are applied.

Of course, applications should still be able to apply styles and inherit from them. Any CSS-in-JS framework worth its salt should address this concern.

Single-page or multi-page apps

Lately, there has been a lot of noise around single-page apps versus multi-page apps. In particular, there are questions about which parts of an application can be fully dynamic, which can be pre-rendered, and which require a bit of both. The bottom line for CSS-in-JS is that styles should be generated where they are needed; either on the server or on the client. Fortunately, this seems to be the case for most frameworks.

CSS frameworks in JS

The first thing you find when considering a CSS-in-JS implementation is the number of options available. Your best choice will be informed, above all, by the JavaScript framework you use. Some CSS-in-JS solutions are specific to a particular responsive framework, while others are agnostic. Even among framework-independent CSS-in-JS libraries, there is often an affinity for a particular framework. Therefore, it should be determined which CSS-in-JS solution is popular within the community that supports the framework you are using.

Another feature to consider when evaluating frameworks is TypeScript support. Not all CSS-in-JS frameworks work with TypeScript, although this is increasingly becoming the norm.

Let’s take a look at some of the best frameworks available.

Stylish components

Stylish components is one of the oldest CSS-in-JS frameworks. It’s tailored to React (although there are efforts to use it elsewhere) and is mostly about styling React components. He is quite active and popular, with over 37,000 stars on GitHub.

You saw an example of styled components in Listing 1.

Emotion

Emotion is independent of frame, although it seems to have an affinity for Svelte. List 2 has a sample of emotion. In the example, note that we’re looking at an inline CSS definition using JavaScript syntax.

Listing 2. Emotion inline CSS-in-JS


import { css, cx } from '@emotion/css'

const color="white"

render(
  
Hover to change color.
)

JSX-style

JSX-style is the default CSS-in-JS solution for Next.js, which unfortunately gives it some inertia. It’s a healthy Git project, with over 7000 stars, but it’s not as active as some of the other projects featured here (it has a branch v2 which seems to be dormant).

JSX-style is an obvious choice when using Next.jsbut it is possible to switch to another React-compatible CSS-in-JS library if desired.

CSS modules

CSS modules is an early and influential implementation of the CSS-in-JS idea. The project on GitHub has over 16,000 stars, but hasn’t been updated for several years. It is framework independent and can be integrated into many popular responsive libraries. For instance, here it is with Vue.

CSS modules are intended to be a general solution which works outside of a framework component system, to create locally scoped styles by default. Note that while CSS Modules sounds like an official spec, it really isn’t – it’s a project with a specific approach on how to do CSS-in-JS.

Double

Downwind CSS is a functional CSS library. It’s something of a darling among JavaScript developers, so it’s bound to be united with a CSS-in-JS approach. Twin combines Tailwind with CSS-in-JS.

Twin allows us to use Tailwind’s classes in multiple CSS-in-JS implementations, as described here. It is an active and growing project, with more than 6,000 stars on GitHub.

The twin has various examples how to integrate it with a variety of frameworks and build tools. For example, this is how it can be combined with Emotion via Webpack.

JSS

JSS is a framework independent approach with over 6,000 GitHub stars. It seems to be quite popular and has good documentation, although it hasn’t seen much activity in the repository lately. JSS is one of the oldest active CSS-in-JS solutions and is in some ways the ancestor of the movement.

Angular

Angular, like many reactive frameworks, supports Component-level CSS. Angular’s system is quite powerful and flexible, with features similar to other libraries. This matches Angular’s all-in-one design philosophy, and it seems to be the most common approach when using Angular. It is however possible to use a CSS-in-JS framework like JSS.

Disadvantages of using CSS in JavaScript

Although CSS-in-JS is very popular, there is a counter trend. The reasons boil down to performance and complexity. A recent article by Sam Magura, an active maintainer of the Emotion framework, describes the issues in detail. The main performance issue is that CSS-in-JS turns CSS into a runtime consideration, increasing the work of the browser and framework at runtime. The result is slower load times and more code that can break.

But the article is also clear about the benefits of CSS-in-JS, which I’ve covered in this article. So the solution is not to reject CSS-in-JS but to find a way to get the benefits while minimizing the drawbacks. The article discusses a variety of possible workarounds for CSS-in-JS performance issues.

Like everything in software, the community continues to push for better ideas. Now we’re looking at ways to keep the benefits of CSS-in-JS while minimizing the drawbacks.

Conclusion

Using a CSS-in-JS framework isn’t always necessary, but it can provide major advantages over using plain CSS or a CSS preprocessor alone. With a variety of solutions to choose from, it should be possible to find one that matches your favorite stack. Additionally, you are likely to come across these frameworks on existing projects, so knowing what they are and how they work is beneficial.

Copyright © 2022 IDG Communications, Inc.