Experiences with CSS-in-JS

Espen Henriksen

Front-end team lead

Oslo Market Solutions

 

espen_dev

esphen

What is CSS-in-JS?

Style attribute

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi nec metus justo. Aliquam erat volutpat.

.. But this is slow

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi nec metus justo. Aliquam erat volutpat.

Injecting classes

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi nec metus justo. Aliquam erat volutpat.

Performant?

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi nec metus justo. Aliquam erat volutpat.

👩‍🎤 Emotion

css function

import React from 'react';
import { css } from 'react-emotion';

const linkClass = css`
  color: #bc128e;
  font-size: 1.25rem;
  margin: 0.5em 0;
  text-decoration: none;
`;

const App = () => (
  <a href="/" className={linkClass}>
    Emotion example!
  </a>
);

babel plugin

import React from 'react';
import { css } from 'react-emotion';

const link = `
  color: #bc128e;
  font-size: 1.25rem;
  margin: 0.5em 0;
  text-decoration: none;
`;

const App = () => (
  <a href="/" css={link}>
    Emotion example!
  </a>
);

Styled components

import React from 'react';
import styled from 'react-emotion';

const Box = styled.div`
  padding: 25px;
  color: white;
  background-color: ${props => props.backgroundColor};
`;

const App = () => (
  <>
    <Box backgroundColor="red">
      Red box
    </Box>
    <Box backgroundColor="blue">
      Blue box
    </Box>
  </>
);

🔥 Advantages of emotion

Unused CSS

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi nec metus justo. Aliquam erat volutpat.

Babel plugin

  • Ahead-of-time compilation
  • Enables more powerful patterns
  • Performance optimization
    • Minification
  • Dead code elimination

Easy to consume

  • Consumers don't need to worry about including CSS files

🤷 Disadvantages

No autoprefixer

  • Uses its own prefixer
  • No support for CSS grid
  • Does not honour browserlist config

No stylelint

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi nec metus justo. Aliquam erat volutpat.

Styled Components

  • Obscures undelying element
    • Is <Wrapper> a div or a section?
    • Semantic markup
    • a11y
  • Composition via props requires styled components
  • Some runtime overhead
import React from 'react';
import { Wrapper } from './styles';

const FooComponent = () => (
  <Wrapper>
    <h1>Hello world!</h1>
    <p>I am using emotion</p>
  </Wrapper>
);

export default FooComponent;

Experiences with CSS-in-JS

By Eline H

Experiences with CSS-in-JS

  • 26