DEV Community

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

Posted on

5 2

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay