LoginSignup
19
13

More than 3 years have passed since last update.

styled componentsのcss prop

Last updated at Posted at 2020-01-04

概要

styled componentscss propがv4から使えます。

今までこのようにちょっとしたstyleの変更をするのにcomponentを作っていたのが

import styled from 'styled-components';

<StyledDiv />

const StyledButton = styled(Button)`
  padding: 0.5em 1em;
`

css propを使うとこのように書くことができるようになります。

<Button
  css="padding: 0.5em 1em;"
/>

importすら必要ありません。

css propの仕組み

なぜかというと、以下のようにcss propが含まれていた場合に、

<Button
  css="padding: 0.5em 1em;"
/>

babel-plugin-styled-componentsが以下のように変換しているからです

import styled from 'styled-components';

const StyledButton = styled(Button)`
  padding: 0.5em 1em;
`

<StyledDiv />

そのため、基本的にstyled componentsでできることはcss propsでもできるはずです。

css propを使うためのセットアップ

css propは上記で説明したようにbabel-plugin-styled-componentsの力によって動いているのでこれを入れないとエラーになってしまいます。

babel-plugin-styled-componentsのインストール

npm install --save-dev babel-plugin-styled-components@latest

.babelrcのpluginsのところにbabel-plugin-styled-componentsを記述します。

/// .babelrc
{
    "plugins": ["babel-plugin-styled-components"]
}

TypeScriptの場合

JavaScriptの場合はbabel-plugin-styled-componentsのセットアップだけでよいのですが、2020年1月4日時点ではTypeScriptの場合css propを使うと以下のようなエラーがでてしまいます。

Property 'css' does not exist on type 'DetailedHTMLProps'

これに対応するにはこのようにTypeScriptの定義ファイルを用意してやる必要があります。

/// styled.d.ts
import { CSSProp } from "styled-components";

...

declare module "react" {
  interface Attributes {
    css?: CSSProp;
  }
}

そのうちこちらのPullRequestがマージされればDefinitelyTyped側に反映されるのでエラーは出なくなると思われます。

参考にしたもの

19
13
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
19
13