LoginSignup
7
10

More than 3 years have passed since last update.

Next.jsにstyled-componentsを導入

Last updated at Posted at 2019-11-04

この記事は下記のことについて書きます。

  • 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
.babelrc
{ 
  "presets": ["next/babel"], 
  "plugins": [
      ["styled-components"]
   ]
}

これで実装ができるのでh1タグにstyleをあてる

TitleStyled.js
import React from 'react';
import styled from 'styled-components';

export const H1 = styled.h1`
  font-size: 1.2rem;
`;
Title.js
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で記述
Layout.tsx
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;
LayoutStyled.js
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って何?となるので、別ファイルで定義

error
Property 'jsx' does not exist on type 'DetailedHTMLProps<StyleHTMLAttributes<HTMLStyleElement>, HTMLStyleElement>'.
next-env.d.ts
import 'react';

declare module 'react' {
  interface StyleHTMLAttributes<T> extends React.HTMLAttributes<T> {
    jsx?: boolean;
    global?: boolean;
  }
}

以上になります。

7
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
10