reactjstypescriptemotion

emotion with react 18 and typescript


The css prop isn't working when I try to use create-react-app with react 18, typescript and emotion 11 — elements are still onstyled, and in the DOM the element has a css attribute whose value is:

You have tried to stringify object returned from css function. It isn't supposed to be used directly (e.g. as value of the className prop), but rather handed to emotion so it can handle it (e.g. as value of css prop).

I can reproduce by setting up a new project:

npx create-react-app test-ts-emotion --template typescript
cd test-ts-emotion 
npm i --save @emotion/react

Then I edit src/App.tsx to be:

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

function App() {
  return (
    <div css={css`background-color: red`}>
      Hello, tester.
    </div>
  );
}

export default App;

and I add jsxImportSource to tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "jsxImportSource": "@emotion/react"
  },
  "include": [
    "src"
  ]
}

Nevertheless, the css prop doesn't work (the element is unstyled and I get the above message as the value for the DOM attribute):

screenshot of error with DOM inspector

You can check this setup at my test repo on Github. I believe I've followed the instructions, but perhaps I'm missing something. Thanks in advance!


Solution

  • If, like me, you're using create-react-app, you must add an explicit configuration to the top of every file:

    /** @jsxImportSource @emotion/react */
    

    This solution is referenced and confirmed in this Emotion issue. It's ultimately a create-react-app bug. A fix exists in this pull request on create-react-app, but it was submitted over a year ago and nobody at Facebook has bothered to look at it, so I doubt it will ever be merged.