CSS prop in Emotion library The css Prop can take styles as template literals or object.
import { css } from '@emotion/react'
function Component() {
return (
<div
css={css`
* {
border: 2px solid grey;
margin: 20px;
padding: 20px;
background-color: white;
}
`}
>
<div>div1</div>
<div
css={{
background: 'red'
}}>
div2
</div>
</div>
)
}
Configuration in Next.js package.json
{
"dependencies": {
"@emotion/react": "^11.10.4",
"@emotion/styled": "^11.10.4",
},
"devDependencies": {
"@emotion/babel-plugin": "^11.10.2",
"@emotion/eslint-plugin": "^11.10.0",
}
}
next.config.js
const nextConfig = {
compiler: {
emotion: true
}
}
module.exports = nextConfig
.babelrc
{
"presets": [
[
"next/babel",
{
"preset-react": {
"runtime": "automatic",
"importSource": "@emotion/react"
}
}
]
],
"plugins": ["@emotion/babel-plugin"]
}
.eslintrc.js
// .eslintrc.js
module.exports = {
env: {
browser: true,
es2021: true,
jest: true
},
extends: [
'plugin:react/recommended',
'standard'
],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaFeatures: {
jsx: true
},
ecmaVersion: 'latest',
sourceType: 'module'
},
plugins: [
'react',
'@typescript-eslint',
'@emotion'
],
rules: {
'react/react-in-jsx-scope': 'off',
'space-before-function-paren': 'off',
'react/prop-types': 'off',
'import/no-absolute-path': 'off',
'react/no-unescaped-entities': 'off',
'react/no-unknown-property': ['error', { ignore: ['css', 'jsx'] }]
}
}
webpack css prop from emotion does not work in react with webpack automatically, like it works with vite for ex. To let it work on top of the file need to put...
/** @jsxImportSource @emotion/react */
Array of object styles
<div
css={[
{
backgroundColor: 'hotpink',
'&:hover': {
color
}
},
isDanger && {
color: 'red'
}
]}
>
div2
</div>