Search code examples
reactjsemotion

What is the benefit of @emotion/react over @emotion/css for a React project?


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.


Solution

  • 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.