LoginSignup
5
3

More than 3 years have passed since last update.

Next.jsにstyled-componentsを適応させる

Posted at

styled-components is 何?

CSS in JSのライブラリの一つ。最近では採用しているプロダクトが増えてきています。cssとjsを同一ファイル内に記述できるため、Reactの設計思想にあるようにコンポーネント単位での管理がスタイルにも可能になります。

導入するメリット

①保守性が高まる(コンポーネント単位でcssを管理)
②cssにjsの値を渡すことができる(動的スタイル)
③コンポーネント単位でスコープが生成される
④重複やスペルミスなどを気にする必要がない
(単一のクラス名をstyled-componentsが作成するため)

styled-componentsの導入手順

①ライブラリの追加



$ npm install --save styled-components
もしくは
$ yarn add styled-components

②以下のようにスタイルを割り当てていきます。

import styled from "styled-components";

export default function FirstPost() {
  const Container = styled.div`
    max-width: 36rem;
    padding: 0 1rem;
    margin: 3rem auto 6rem;
  `;

  const Text = styled.div`
    //引数に色が渡すことができる
    color: ${props => props.color ? props.color : "dark"};
  `;  

  return (
    <Container>
      <Text color="red">Hello!</Text>
    </Container>
  );
}

③babelのプラグインの設定
Next.jsとstyled-componentsが実行される前提とする環境が異なります。(styled-componentは元々クライアント側で動くことを前提としています)そのため、サーバーサイドでもstyled-componentsが働くようにしていきます。

$ npm install --save-dev babel-plugin-styled-components
もしくは
$ yarn add -D babel-plugin-styled-components

④プロジェクトのルートに.babelrcを作成

:.babelrc
{
    "presets": [
      "next/babel"
    ],
    "plugins": [
      [
        "babel-plugin-styled-components",
        {
          "ssr": true,
          "displayName": true,
        }
      ]
    ]
  }

参考にさせていただいた記事

Next.jsにstyled-componentsを取り込む方法【Babelの設定が必要】

styled-components(CSS in JS)をやめた理由と、不完全なCSS Modulesを愛する方法

Reactのプロジェクトならstyled-components使うのがいいかも

5
3
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
5
3