この記事は下記のことについて書きます。
- Next.jsにstyled-componentsの導入方法
- Next.jsのbodyにglobalなcssの設定方法
参考にした記事はこちらになります。
styled-componentについて
「これからのReactのスタイリングにはStyled Componentsが最高かもしれない」に書かれているとおりになります。
cssの定義を、class属性を利用してカプセル化して再利用しやすいようにするための仕組みです。StyledComponentsもこの流れではありますが、外部cssファイルではなくjsxファイルに定義するためそのファイル内でReactコンポーネントとレイアウト定義がカプセル化され感覚的にとても扱いやすくなります。
外部ファイルのglobalで管理されたcssを適用するのではなく、scopedされたcomponentでcssを管理/適用するということですね。
Next.jsにstyled-componentsの導入方法
styled-components
をinstall
$ yarn add styled-components
componentのclassNammeをハッシュさせるためにbabel-plugin-styled-components
をインストールして.babelrc
に設定
$yarn add -D babel-plugin-styled-components
{
"presets": ["next/babel"],
"plugins": [
["styled-components"]
]
}
これで実装ができるのでh1
タグにstyleをあてる
import React from 'react';
import styled from 'styled-components';
export const H1 = styled.h1`
font-size: 1.2rem;
`;
import React from 'react';
import { H1 } from './TitleStyled';
const H1Title = () => (
<H1>
hoge
</H1>
);
export default H1Title;
Next.jsのbodyにglobalなcssの設定方法
componentごとのstyleはstyled-components
でカプセル化させますが、globalなcssにreset.css
を適用したいのでその設定方法になります。
- 公式サイトを参考に
<head>
タグの直下に指定 - TypeScriptで記述
import * as React from 'react';
import Head from 'next/head';
import LayoutStyled from "./LayoutStyled";
const Layout: React.FunctionComponent<LayoutProps> = ({ children}) => (
<>
<Head>
<meta charSet="UTF-8" />
<title>タイトル</title>
<meta name="description" content="" />
<meta name="keywords" content="" />
</Head>
<LayoutStyled />
{children}
</>
);
export default Layout;
import React from 'react';
const LayoutStyled = () => (
<style jsx global>
{
`
body {
color: #1a1a1a;
font-family: 'Hiragino Kaku Gothic ProN', 'メイリオ', sans-serif;
font-size: 14px;
line-height: 1.4;
}
`
}
</style>
);
export default LayoutStyled;
この記述だとTypeScriptでstyle
って何?となるので、別ファイルで定義
Property 'jsx' does not exist on type 'DetailedHTMLProps<StyleHTMLAttributes<HTMLStyleElement>, HTMLStyleElement>'.
import 'react';
declare module 'react' {
interface StyleHTMLAttributes<T> extends React.HTMLAttributes<T> {
jsx?: boolean;
global?: boolean;
}
}
以上になります。