DEV Community

Mehdi Najafi
Mehdi Najafi

Posted on

4 1

How to use emotion css prop in vite.

The primary way to style elements with emotion is the css prop.

const Component = () => {
  return (
    <div
      css={{
        backgroundColor: "hotpink",
        "&:hover": {
          color: "lightgreen",
        },
      }}
    >
      This has a hotpink background.
    </div>
  );
};

Enter fullscreen mode Exit fullscreen mode

1. Install Dependencies

For using css prop in vite project first install @emotion/babel-plugin:

yarn add -D @emotion/babel-plugin
Enter fullscreen mode Exit fullscreen mode

2. Update vite.config.js

Here, we add the @emotion/babel-plugin to @vitejs/plugin-react babel option. Also for using css prop we have to tell vite to use Emotion's jsx function by setting jsxImportSource to @emotion/react.

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [
    react({
      jsxImportSource: "@emotion/react",
      babel: {
        plugins: ["@emotion/babel-plugin"],
      },
    }),
  ],
});

Enter fullscreen mode Exit fullscreen mode

Now you can use css prop in your react app.

TypeScript

If you are using TypeScript in your project first add "jsxImportSource": "@emotion/react" to your tsconfig.json file.

{
  "compilerOptions": {
    // ...
    "jsxImportSource": "@emotion/react"
  }
}
Enter fullscreen mode Exit fullscreen mode

Then for using typed css prop update your vite-env.d.ts.

/// <reference types="vite/client" />
/// <reference types="@emotion/react/types/css-prop" />
Enter fullscreen mode Exit fullscreen mode

Billboard image

Synthetic monitoring. Built for developers.

Join Vercel, Render, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (1)

Collapse
 
blair profile image
Blair

Thanks for this!

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay