15

If I install emotion/css then the API is nice and clear:

package.json:

"dependencies": {
  "@emotion/css": "^11.1.3",

React component:

import React from "react";
import { css } from "@emotion/css";

const someStyle = css`
    display: none;
`

function MyComponent() {
  return (
    <div className={someStyle} />
  );
}

However according to the docs you should install @emotion/react: https://emotion.sh/docs/introduction

package.json:

"dependencies": {
  "@emotion/react": "^11.4.1",

Now the API is a lot more messy:

import React from "react";
/** @jsx jsx */
import { jsx, css } from "@emotion/react";

const someStyle = css`
  display: none;
`;

function MyComponent() {
  return (
    <div css={someStyle} />
  );
}

Not only do you need a comment /** @jsx jsx */, but you also have to import jsx even though it's not used. In my IDE this means I get a lint warning by my React import.

What is the benefit of the recommended way? Im tempted to ignore the documentation and do it the old way.

chantey
  • 4,252
  • 1
  • 35
  • 40
Evanss
  • 23,390
  • 94
  • 282
  • 505

2 Answers2

6

Both are valid and each approach has its benefits:

emotion/css:

  • use vanilla react className prop
  • no custom jsx parser
  • no babel config or file pragmas
  • no extra typescript config
  • generate class names outside of react components

emotion/react:

  • zero config for @emotion/cache
  • easy server side rendering
  • easy access to theme through css function

More resources

chantey
  • 4,252
  • 1
  • 35
  • 40
4

The jsx pragma/import is required because the css prop is provided by a wrapper around React.createElement - without that transform being applied, the css prop would not work.

That said, including it in every file is tedious - that's why there is a babel plugin that does it for you.

{
  "presets": ["@emotion/babel-preset-css-prop"]
}

With regards to the benefits of using this method over the stock emotion package, the docs list some on the page you linked:

  • CSS prop support
    • Similar to the style prop but adds support for nested selectors, media queries, and auto-prefixing.
    • Allows developers to skip the styled API abstraction and style components and elements directly.
    • The css prop also accepts a function that is called with your theme as an argument allowing developers easy access to common and customizable values.
    • Reduces boilerplate when composing components and styled with emotion.
  • Server side rendering with zero configuration.
  • Theming works out of the box.
  • ESLint plugins available to ensure proper patterns and configuration are set.
Joe Clay
  • 33,401
  • 4
  • 85
  • 85
  • 1
    It's not my original question but FYI that solution doesn't appear to work (at least as is). – Evanss Aug 15 '19 at 09:20