DEV Community

gortron
gortron

Posted on

Using Emotion for CSS-in-JavaScript

Introduction

You're already familiar with CSS, and likely with CSS-supersets like sass and less, which add much-needed utility and convenience to CSS. But some frontend developers are turning to CSS-in-JS, an increasingly common pattern for styling web applications.

It's easy to understand why this approach is gaining traction. Imagine you've been tasked to make a button component with React, and you've been given some specs for its styling. You have two options:

1) Separate JS and CSS

Write the Button.js React component and give it a class name like <Button className="styled">, then write the component-specific css in a separate file.

// Button.js
import React from 'react'
const Button = () => (
  return <button className="styled">Click Me</button>
)
/* sass or less which allows for logic statements */
button.styled {
  padding: 32px;
  background-color: hotpink;
  font-size: 24px;
  border-radius: 4px;
  &:hover {
    color: white;
  }
}

But, if another engineer needs to debug the component or change styling in the future, they need to work in both the JS and CSS files. This is a negligible issue for a simple component, but a more onerous task for a brand re-work.

2) CSS-in-JS

Write the component and styling logic in one file.

// Button.js
import React from 'react'
import { css } from 'emotion'

const Button = () => (
  return <button css={css`
    padding: 32px;
    background-color: hotpink;
    font-size: 24px;
    border-radius: 4px;
    &:hover {
      color: white;
    }`}
  >Click Me</button>
)

I haven't touched on other major benefits of CSS-in-JS, such as the ease with which you can pass styling arguments as props to your components, e.g. <Button big pink>, or making styled components e.g. StyledButton = button.styled{...}.

As an aside, Emotion is a popular library (see also: styled-components) for CSS-in-JS, and well worth a look. (I borrowed their styling for this blog post!)

Conclusion

These two schools exhibit a philosophical question: is styling something "other" than the object that is styled, or is styling an inextricable property of the thing that is styled? In my opinion, it's the latter. So, to my taste, CSS-in-JS makes more organizational sense to me. (A poor analogy: imagine having to look away from a house to figure out what color it is.)

Beyond that, choosing between separating JS and CSS and using CSS-in-JS is a tradeoff between strict adherence to separation of concerns, and developer convenience/experience.

This to me seems like a broader trend of everything-in-JS. JS seems to continue to evolve into do-anything language. Consider the popularity of Node.js, and the recent announcement of TensorFlow.js.

Top comments (0)