npx create-next-app@latest --use-npm next-emotion-minimal-app
npm install @emotion/react
{
"compilerOptions": {
// emotion
"jsx": "preserve",
"jsxImportSource": "@emotion/react",
components/SampleCss.tsx
'use client';
import { css } from '@emotion/react';
import { FC } from 'react';
export const SampleCss: FC = () => {
return (
<div
css={css`
color: green;
font-size: 48px;
font-weight: bold;
`}
>
SampleCss
</div>
);
};
import { css } from '@emotion/react';
const fontLarge = css`
font-size: 48px;
`;
const colorGreen = css`
color: green;
`;
export default function Home() {
return (
<>
<div css={[fontLarge, colorGreen]}>home</div>
</>
);
}
import { css } from '@emotion/react';
const fontLarge = css`
font-size: 48px;
`;
const myFont = css`
${fontLarge}
color: blue;
`;
export default function Home() {
return (
<>
<div css={myFont}>home</div>
</>
);
}
import type { AppProps } from 'next/app';
import { css, Global } from '@emotion/react';
const globalStyle = css`
body {
font-family: 'Helvetica Neue', Arial, 'Hiragino Kaku Gothic ProN',
'Hiragino Sans', Meiryo, sans-serif;
}
`;
export default function App({ Component, pageProps }: AppProps) {
return (
<>
<Global styles={globalStyle}></Global>
<Component {...pageProps} />
</>
);
}
src/pages/index.tsx
import { useState } from 'react';
import { css } from '@emotion/react';
type MyFont = {
colored:boolean
}
export default function Home() {
const [colored, setColored] = useState<boolean>(false);
const myFont = ({ colored }:MyFont) => css`
border: solid 1px black;
border-radius: 10px;
padding: 16px;
cursor: pointer;
${colored &&
`
background-color: #413F42;
color: white;
`}
`;
return (
<>
<button
onClick={() => {
setColored(!colored);
}}
>
色変更
</button>
<div css={myFont({ colored: colored })}>home</div>
</>
);
}
npm install @emotion/styled
こちらで css から js object に 変換します
https://transform.tools/css-to-js
SampleStyled.tsx
'use client';
import styled from '@emotion/styled';
const MyTitle = styled.h1`
border: 10px solid blue;
padding: 2rem;
font-size: 3.5rem;
margin: 0px;
color: blue;
`;
export function SampleStyled() {
return <MyTitle as={'button'}>home</MyTitle>;
}
as={'button'} で 出力時にタグを h1 から button に変更しています
react17 で emotionを動かすには
1. tsconfig.json
"jsx": "preserve",
"jsxImportSource": "@emotion/react",
2. コンポーネントファイルの先頭に jsxプラグ魔を追加
/** @jsxImportSource @emotion/react */
3. コンポーネントファイルの先頭に jsxプラグマを追加したくない場合はこちら
https://qiita.com/y-suzu/items/2d3fcf5414f7b418f05a
https://emotion.sh/docs/@emotion/babel-preset-css-prop
https://qiita.com/xrxoxcxox/items/17e0762d8e69c1ef208f
@emotion/reactでのスタイル指定方法 - Qiita