styled-componentsはよく使われるcss in jsクラスライブラリです。同種のクラスライブラリと同様に、変数、ループ、関数など、ネイティブのcssにはない機能の問題をjs-enableによって解決しています。sass&lessのようなプリプロセッサは、cssの制限のいくつかに対処することができますが、それでも新しい構文を学習してコンパイルする必要があり、その複雑なwebpackの設定は常に開発者にとって嫌なものです。Styled-componentsはこれらの問題を解決し、Reactテクノロジースタックのプロジェクトに非常に適しています。
インストール
yarn add styled-components
- インストール TS ステートメント
yarn add --dev @types/styled-components
例
import React from 'react';
import styled from 'styled-components';
// Create a <Title> react component that renders an <h1> which is
// centered, palevioletred and sized at 1.5em
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
// Create a <Wrapper> react component that renders a <section> with
// some padding and a papayawhip background
const Wrapper = styled.section`
padding: 4em;
background: papayawhip;
`;
// Use them like any other React component - ただし're styled!
<Wrapper>
<Title>Hello World, this is my first styled component!</Title>
</Wrapper>
継承
const Button = styled.button`
color: palevioletred;
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid palevioletred;
border-radius: 3px;
`;
// A new component based on Button, but with some override styles
const TomatoButton = styled(Button)`
color: tomato;
border-color: tomato;
`;
Styling any component
// This could be react-router-dom's Link for example
const Link = ({ className, children }) => (
<a className={className}>
{children}
</a>
);
const StyledLink = styled(Link)`
color: palevioletred;
font-weight: bold;
`;
render(
<div>
<Link>Unstyled, boring Link</Link>
<br />
<StyledLink>Styled, exciting Link</StyledLink>
</div>
);
概要
- コンテナとコンポーネントの概念が導入され、コンポーネントとスタイルの間のマッピングが削除され、関心事項の分離モデルに準拠しています;
- スタイルはjsファイルに記述され、jsのcssファイルへの依存を減らします。
- コンポーネント間の継承をサポートし、コードの再利用を容易にし、保守性を向上させます;
- ネーミングに悩む必要はありません。