DEV Community

Cover image for Use Emotion with React Typescript ^4.1
fabiangamboa95
fabiangamboa95

Posted on

Use Emotion with React Typescript ^4.1

Problem

Hello friends. I just spend over 20mins searching for the right way to configure react-typescript to get the emotion library working. And I couldn't find the single place where the answer lies.
So now that I gathered enough, you don't need to spend that time over such a simple issue.

Solution

1 - After you install the proper package "@emotion/react". You need to head over your tsconfig.json file and make sure you have the following lines under "compilerOptions":

 "jsx": "react-jsx", "jsxImportSource": "@emotion/react" 
Enter fullscreen mode Exit fullscreen mode

2 - Then as a requirement you must have these "comments" at the top of every .tsx file you want to use the css functionality.

/** @jsxRuntime classic */ /** @jsx jsx */ 
Enter fullscreen mode Exit fullscreen mode

3 - Don't forget to always import { jsx } from '@emotion/react'

A complete usage example would be:

/** @jsxRuntime classic */ /** @jsx jsx */ import { jsx, css } from "@emotion/react"; const App = () => { return ( <div css={css` padding: 32px; background-color: hotpink; font-size: 24px; border-radius: 4px; &:hover { color: ${color}; } `} >Hover to change color.</div> ); }; export default App; 
Enter fullscreen mode Exit fullscreen mode

There you go! If it was useful for you consider to smash that heart, that way I'll keep posting stuff.

Top comments (0)