6

5 CSS-in-JS Frameworks to use in 2021

 3 years ago
source link: https://blog.openreplay.com/5-css-in-js-frameworks-to-use-in-2021
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

As web development continues massive evolving, new ways of doing things emerge, and communities get built around them. Handling frontend development with JS frameworks, styling components have been all about having separately dedicated stylesheets for each component which are now applied to the DOM.

Introduction

CSS can be really exhausting for developers, maintaining styles across components and context switching can become a chore, you can also relate to this if you have spent some time trying to center a div or a button before. Developers who primarily work with JavaScript started to innovate around styling and asking what if it can also be done in JS.

CSS-in-JS is a new approach to styling using JavaScript to style components in-line, on compile, the JS is parsed and CSS rules are generated and pushed to the DOM. This means you do not really have to carry the burden of the CSS learning curve, neither do you need to fully understand it as it is now totally abstracted for you. This approach promises to be more maintainable, easier to use (as you stick to the JS you already know) and some even have special features built to enhance CSS.

In today’s post, we will be looking at a few of these CSS-in-JS frameworks you can try out in your workflow right away.

Styled Components

null

This is the most popular CSS-in-JS library that currently exists and the term CSS-in-JS was also made very popular by Styled Components. With widespread usage, over 35,000 stars on GitHub with over 10m projects using it per month Styled Components lets you define CSS styles inline using ES6 template literals. Popular in the React community for styling React components easily. This is how easy a button is styled:

1import styled from 'styled-components'
2const Button = styled.button``

The style definition would look like this:

1const Button = styled.button`
2 background: transparent;
3 border-radius: 3px;
4 border: 2px solid palevioletred;
5 color: palevioletred;
6 margin: 0 1em;
7 padding: 0.25em 1em;

Styled Components comes with a lot of advantages asides we general ones we already mentioned above, you can do selector nesting, just like with SASS. You also never need to worry about class name bugs as it generates unique class names automatically and manages them as they go in and out of the DOM.

Emotion

null

The first special thing about Emotion as a CSS-in-JS library is that is framework agnostic so you can use it in Vue and Angular projects as well as React too. With over 13,000 stars on GitHub Emotion is a very flexible library that is built on other CSS-in-JS libraries and another great thing about it is how it is predictable so even with little knowledge of CSS, you can start using it without any issues. It has a really cool documentation, the vue-style that you are probably already familiar with and is very performant.

A hover button in Emotion looks like this:

1import { css, cx } from '@emotion/css'
3const color = 'white'
5render(
6 <div
7 className={css`
8 padding: 32px;
9 background-color: hotpink;
10 font-size: 24px;
11 border-radius: 4px;
12 &:hover {
13 color: ${color};
16 >
17 Hover to change color.
18 </div>

Open Source Session Replay

Debugging a web application in production may be challenging and time-consuming. OpenReplay is an Open-source alternative to FullStory, LogRocket and Hotjar. It allows you to monitor and replay everything your users do and shows how your app behaves for every issue. It’s like having your browser’s inspector open while looking over your user’s shoulder. OpenReplay is the only open-source alternative currently available.

OpenReplay

Happy debugging, for modern frontend teams - Start monitoring your web app for free.

Stitches

null

This is a very interesting one, with almost 4,000 stars on GitHub Stitches is a CSS-in-JS library that runs in near-zero runtime. It supports server-side rendering and has variants support. Basically, CSS was re-imagined as a JS library with stitches. It is also framework agnostic so you can use it with any frontend development library. It ships with smart tokens and even custom CSS properties.

With Stitches, you do not have to download an entire library because it does style injection. With a fully-typed API, token-aware properties, and custom utils, Stitches offers a fun and intuitive experience all-round.

A simple button is created like this:

1import { styled } from '@stitches/react';
3const Button = styled('button', {
4 backgroundColor: 'gainsboro',
5 borderRadius: '9999px',
6 fontSize: '13px',
7 padding: '10px 15px',
8 '&:hover': {
9 backgroundColor: 'lightgray',
11});

Radium

null

Radium took a kind of radical approach, eliminating CSS totally for inline styles and making all of those styles global. This basically provides us with scoped styling without using selectors, eliminating dead code or chances of repeattition and being totally expressive. You might say inline styles are limited by default, that is correct but Radium offers a standard interface that deals with issues like media queries and browser or mouse states like click or hover.

A button in Radium looks like this:

1import Radium from 'radium';
2import React from 'react';
3import color from 'color';
5class Button extends React.Component {
6 static propTypes = {
7 kind: PropTypes.oneOf(['primary', 'warning']).isRequired
10render() {
11 // Radium extends the style attribute to accept an array. It will merge
12 // the styles in order. We use this feature here to apply the primary
13 // or warning styles depending on the value of the `kind` prop. Since its
14 // all just JavaScript, you can use whatever logic you want to decide which
15 // styles are applied (props, state, context, etc).
16 return (
17 <button style={[styles.base, styles[this.props.kind]]}>
18 {this.props.children}
19 </button>
24Button = Radium(Button);
26// You can create your style objects dynamically or share them for
27// every instance of the component.
28var styles = {
29 base: {
30 color: '#fff',
32// Adding interactive state couldn't be easier! Add a special key to your
33 // style object (:hover, :focus, :active, or [@media](http://twitter.com/media)) with the additional rules.
34 ':hover': {
35 background: color('#0074d9')
36 .lighten(0.2)
37 .hexString()
41primary: {
42 background: '#0074D9'
45warning: {
46 background: '#FF4136'

It was built for React applications, most of the CSS-in-JS libraries have dedicated React libraries too.

null

JSS is a CSS abstraction in JavaScript, it dynamically outputs rules based on component state. It is super lightweight and one great thing about it is integrations, it has a React integration, a Styled Component integration and a lot of plugins too. Remember how some CSS-in-JS generates styles and injects them inline in the DOM, JSS does it the old fashioned way output a master stylesheet before injecting it. There are a lot of useful plugins you can use to achieve the functionality available in other CSS-in-JS libraries like nesting, global selectors, plugin isolation etc.

A button looks like this:

1import React from 'react'
2import {render} from 'react-dom'
3import {createUseStyles} from 'react-jss'
5// Create your Styles. Remember, since React-JSS uses the default preset,
6// most plugins are available without further configuration needed.
7const useStyles = createUseStyles({
8 myButton: {
9 color: 'green',
10 margin: {
11 // jss-expand gives more readable syntax
12 top: 5, // jss-default-unit makes this 5px
13 right: 0,
14 bottom: 0,
15 left: '1rem'
17 '& span': {
18 // jss-nested applies this to a child span
19 fontWeight: 'bold' // jss-camel-case turns this into 'font-weight'
22 myLabel: {
23 fontStyle: 'italic'
27const Button = ({children}) => {
28 const classes = useStyles()
29 return (
30 <button className={classes.myButton}>
31 <span className={classes.myLabel}>{children}</span>
32 </button>
36const App = () => <Button>Submit</Button>
38render(<App />, document.getElementById('root'))

Conclusion

We have gotten acquainted with the concept of CSS-in-JS and how it can be useful to us in our workflow. We also took a look at a few CSS-in-JS libraries we can start using today. You can follow the State of CSS survey here where thousands of developers share their feeedback every year. Which is your favourite and why?


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK