メインコンテンツまでスキップ

Styled Componentsの書き方

Styled Components は、JavaScript で CSS を書けるようにするライブラリです。CSS をコンポーネントに紐付けることで、スタイルの再利用性や保守性を高めることができます。

基本的な書き方

最も基本的な書き方は、styled.div のように styled 関数を使って要素を定義し、その中に CSS を記述します。

import styled from 'styled-components';

const MyDiv = styled.div`
color: blue;
font-size: 16px;
`;

function MyComponent() {
return <MyDiv>Hello, Styled Components!</MyDiv>;
}

export default MyComponent;

この例では、MyDiv というコンポーネントが作成され、color: blue;font-size: 16px; のスタイルが適用されます。

Props を利用した動的なスタイル

Props を利用することで、コンポーネントの props に基づいてスタイルを動的に変更できます。

import styled from 'styled-components';

const Button = styled.button`
background-color: ${props => props.primary ? 'blue' : 'white'};
color: ${props => props.primary ? 'white' : 'black'};
padding: 10px 20px;
border: none;
cursor: pointer;
`;

function MyComponent() {
return (
<>
<Button primary>Primary Button</Button>
<Button>Secondary Button</Button>
</>
);
}

export default MyComponent;

この例では、primary という props が true の場合、背景色が青色、文字色が白色になります。primaryfalse の場合は、背景色が白色、文字色が黒色になります。

テーマの利用

テーマを利用することで、アプリケーション全体で一貫したスタイルを維持できます。

まず、テーマオブジェクトを定義します。

const theme = {
primaryColor: 'blue',
secondaryColor: 'gray',
fontSize: '16px',
};

次に、ThemeProvider を利用して、コンポーネントツリー全体にテーマを適用します。

import { ThemeProvider } from 'styled-components';

function App() {
return (
<ThemeProvider theme={theme}>
{/* コンポーネントツリー */}
</ThemeProvider>
);
}

最後に、コンポーネント内でテーマの値を参照します。

import styled from 'styled-components';

const Heading = styled.h1`
color: ${props => props.theme.primaryColor};
`;

function MyComponent() {
return <Heading>Hello, Styled Components!</Heading>;
}

この例では、primaryColor というテーマの値が Heading コンポーネントの文字色として使用されます。

拡張 (Extend)

既存のスタイルを拡張して新しいスタイルを作成できます。

import styled from 'styled-components';

const BaseButton = styled.button`
padding: 10px 20px;
border: none;
cursor: pointer;
`;

const PrimaryButton = styled(BaseButton)`
background-color: blue;
color: white;
`;

function MyComponent() {
return (
<>
<BaseButton>Base Button</BaseButton>
<PrimaryButton>Primary Button</PrimaryButton>
</>
);
}

この例では、PrimaryButtonBaseButton のスタイルを継承し、追加で background-colorcolor のスタイルを定義しています。

公式ドキュメント

https://styled-components.com/docs/basics