npx create-next-app@latest --use-npm next-emotion-minimal-app
npm install @emotion/react
{
"compilerOptions": {
// emotion
"jsx": "preserve",
"jsxImportSource": "@emotion/react",
src/pages/index.tsx
import { css } from '@emotion/react';
export default function Home() {
return (
<>
<div
css={css`
color: red;
font-size: 48px;
font-weight: bold;
`}
>
home
</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
src/pages/index.tsx
import styled from '@emotion/styled';
const MyTitle = styled.h1`
font-size: 3.5rem;
margin: 0px;
color: blue;
`;
export default function Home() {
return (
<>
<MyTitle as={'button'}>home</MyTitle>
</>
);
}
as={'button'} で 出力時にタグを h1 から button に変更しています