Files
TechradarDev/radar/2021-01-01/css-in-js.md
2021-06-17 14:38:36 +02:00

1.3 KiB

title, ring, quadrant
title ring quadrant
CSS-in-JS trial methods-and-patterns

CSS-in-JS is a method where JavaScript is used to style components. The first libraries which implemented these technique where Styled-Components, Emotion & JSS.

Example:

const Button = styled.button`
  display: inline-block;
  padding: 0.5rem 0;
  background: transparent;
  color: white;
  border: 2px solid white;

  ${(props) =>
    props.primary &&
    css`
      background: white;
      color: black;
    `}
`;

return <Button primary>Click me</Button>;

Advantages of CSS-in-JS

  • Local Scoping instad of global namespace
  • No classname to element mapping
  • Use the full power of JavaScript to enhance CSS (loops, variables & more)
  • Dynamic syling & Theming (Access to state or props)
  • TypeScript Support

Disadvantages of CSS-in-JS

  • Runtime cost when using dynamic styling
  • Slightly different syntax than traditional CSS (object syntax vs template literals)
  • Can add an extra layer of complexity

In the meantime CSS-in-JS has evolved even more. The are some libraries which leverages nearly zero-runtime costs such as Stiches or Vanilla Extract while still providing an excellence developer experience with TypeScript.