3

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!

Noah
  • 496
  • 5
  • 12
  • https://stackoverflow.com/questions/72272133/unable-to-setup-emotion-with-typescript-jsximportsource this may help – Notics Jun 25 '22 at 07:15

2 Answers2

0

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.

Noah
  • 496
  • 5
  • 12
0

A bit late answer, but relevant; ye could keep your tsconfig.json configuration and just add NPM dependency to your project:

npm i @emotion/babel-preset-css-prop --save-dev

finally, add a configuration to your babel.config.json as follows:

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

P.S. repo to minimal React 18 + TypeScript + Emotion template:- github repo

Benjamin Buch
  • 4,752
  • 7
  • 28
  • 51
Dmitro
  • 11
  • 2