LoginSignup
15
8

More than 3 years have passed since last update.

どちゃくそ簡単なstyled-components入門

Last updated at Posted at 2018-10-12

目的

styled-componentsって聞いたことあるけどまだちょっと触った事ない・・・
CSS in JSって何・・・?
小難しい理論とかいいんでとりあえず動かしたい

みたいな方向けにstyled-componentsめっちゃ簡単だよっていう記事です。
裏側まで100%理解しているわけではない初心者記事なので変なところがあったらツッコミいただけると嬉しいですm(_ _)m

前提

以下のような方向けです。
- React触ったことある
- スタイル付けは外部にCSSファイル作ってやってた

流れ

STEP 0) とりあえず、react環境が用意されているとします。(なければ、create-react-appでいいので作っちゃいましょう)
STEP 1) styled-componentsをインストールし、importします。
STEP 2) JSXのタグ部分を、任意の名前に置き換えます。
STEP 3) 上記の名前をconstで宣言し、スタイルをつけます。

STEP 0

まずはこういう感じでコンポーネントがあるとします。

// js/App.js
import React from 'react';

export class App extends React.Component {
  render() {
    return (
      <div>hello styled-component!</div>
    )
  }
}

STEP 1

では早速styled-componentsを導入しましょう。

npm install --save styled-components

ついでにbabel pluginも入れておきます。

npm install --save-dev babel-plugin-styled-components
// .babelrc
{
  "presets": ["@babel/preset-env", "@babel/preset-react"],
  "plugins": ["babel-plugin-styled-components"]
}

コンポーネントに戻って、styled-componentsをimportしましょう。
export defaultがstyledになっていますのでそのままimportします。

// js/App.js
import React from 'react';
import styled from 'styled-components';

export class App extends React.Component {
  render() {
    return (
      <div>hello styled-component!</div>
    )
  }
}

STEP 2

reactコンポーネントで返される仮想DOMを、divからTitleに変更します。
(名前はなんでも大丈夫ですが、定数として扱うので、他の定数名と被らないようにしましょう。)

// js/App.js
import React from 'react';
import styled from 'styled-components';

export class App extends React.Component {
  render() {
    return (
      <Title>hello styled-component!</Title>
    )
  }
}

STEP 3

下部分に、constで先ほど付けた名前を定義します。
styled.の後に好きなタグ名をつける事で、そのタグとしてHTMLが出力されるようになります。
あとは、``の中に通常のCSSと同じように記述するだけです。

// js/App.js
import React from 'react';
import styled from 'styled-components';

export class App extends React.Component {
  render() {
    return (
      <Title>hello styled-component!</Title>
    )
  }
}

// styled-components
const Title = styled.h1`
  font-size: 34px;
`;

ね、簡単でしょ?


ちなみに、sass(scss)記法がそのまま使えます。

// styled-components
const Title = styled.h1`
  font-size: 34px;
  strong {
    color: #f0f011; // Titleの中の<strong>タグで囲まれた部分だけ色が変わる
  }
`;

発展

propsに応じてスタイルを出し分ける
syntax highlighting(自分の環境にあったモノを導入しましょう!)

余談

そもそもstyled-componentsを使うべきか否か、というのはケースバイケースかと思います。
個人的にはコンポーネント単位でファイルをまとめられるのでこの方が好きですが
実際どう実装すべきかはプロダクト・プロジェクトの設計によりけりでしょう。

15
8
1

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
15
8