Inline CSS using Emotion in React

Viewed 1429

Broadly speaking, I appear to have found a discrepancy in the Emotion documentation. On the Introduction page, we are introduced to styling components with the following syntax,

import { css, cx } from 'emotion'

const color = 'white'

render(
  <div
    className={css`
      padding: 32px;
      background-color: hotpink;
      font-size: 24px;
      border-radius: 4px;
      &:hover {
        color: ${color};
      }
    `}
  >
    Hover to change color.
  </div>
)

I'd like to note, that the way the inline CSS is added via the following syntax,

className={css` <- CSS Goes Here ->`}

However, this syntax failed to work when we implemented in our application. Reading the documentation further, in particular the CSS Prop page, we found this syntax,

/** @jsx jsx */
import { jsx } from '@emotion/core'

render(
  <div
    css={{
      backgroundColor: 'hotpink',
      '&:hover': {
        color: 'lightgreen'
      }
    }}
  >
    This has a hotpink background.
  </div>
)

Or, for the sake of clarity,

css={{ <- CSS Goes Here -> }}

This format worked right out of the box, which leaves me wondering, why does this one work but the former doesn't? Are we missing something? Could someone please explain the difference between the two?

1 Answers

There are two ways to install emotion for your React app, as described in your first link - framework agnostic (@emotion/css), or specifically for React (@emotion/react). Scrolling down a little beyond the React header, you'll find

@emotion/react css prop documentation

Therefore, className={css` is the syntax for the framework-agnostic, less specific package. Meanwhile, css={{... uses a different approach. Here, instead of adding a class to your component, you are using the css prop from the React package, which is

evaluated and the computed class name is applied to the className prop.

Related