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>
);
};
1. Install Dependencies
For using css prop in vite project first install @emotion/babel-plugin:
yarn add -D @emotion/babel-plugin
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"],
},
}),
],
});
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"
}
}
Then for using typed css prop update your vite-env.d.ts
.
/// <reference types="vite/client" />
/// <reference types="@emotion/react/types/css-prop" />
Top comments (1)
Thanks for this!