Styled ComponentsでReactアプリのスタイリングをモジュール化する

Styled Componentsは、ReactアプリケーションでCSSをJavaScript内に直接記述し、コンポーネントごとにスタイルをモジュール化するためのライブラリです。本記事では、その基本的な使い方から高度なテクニックまでを解説します。
目次
1. Styled Componentsとは
Reactコンポーネントにスタイルを適用するためのライブラリで、CSS-in-JSアプローチを採用しています。
import styled from 'styled-components';
const Button = styled.button`
background: blue;
color: white;
`;
function App() {
return <Button>Click me</Button>;
}
2. インストール方法
Styled Componentsをプロジェクトに追加します。
npm install styled-components
3. 基本的な使い方
スタイル付きコンポーネントを作成し、再利用する方法です。
const Container = styled.div`
display: flex;
justify-content: center;
`;
4. Propsを使用した動的スタイリング
Propsを使ってスタイルを動的に変更できます。
const Button = styled.button`
background: ${props => (props.primary ? 'blue' : 'gray')};
`;
5. グローバルスタイルの設定
GlobalStyleを使ってアプリ全体のスタイルを設定できます。
import { createGlobalStyle } from 'styled-components';
const GlobalStyle = createGlobalStyle`
body {
margin: 0;
padding: 0;
}
`;
6. テーマの適用
ThemeProviderを使ってテーマを一括管理できます。
import { ThemeProvider } from 'styled-components';
const theme = {
primary: 'blue',
};
function App() {
return (
<ThemeProvider theme={theme}>
<Button>Click me</Button>
</ThemeProvider>
);
}
7. スタイルの継承
既存のコンポーネントスタイルを継承して新しいコンポーネントを作成できます。
const PrimaryButton = styled(Button)`
font-size: 1.5em;
`;
8. コンポーネント間のスタイル依存
親コンポーネントからスタイルを継承できます。
9. スタイルの条件分岐
条件に応じて異なるスタイルを適用します。
10. アニメーションの適用
keyframesを使用してアニメーションを追加します。
import { keyframes } from 'styled-components';
const fadeIn = keyframes`
from {
opacity: 0;
}
to {
opacity: 1;
}
`;
const AnimatedDiv = styled.div`
animation: ${fadeIn} 1s ease-in;
`;
11. スタイルのパフォーマンス最適化
不要なレンダリングを防ぐテクニック。
12. まとめ
Styled Componentsを使うことで、コンポーネントごとにスタイルを明確に分離し、再利用性と保守性を高めることができます。
-
前の記事
Oracle Database テーブルにあるコメントを確認する 2025.02.20
-
次の記事
PHPエラー『Parse Error: Syntax Error』の解決方法 2025.02.20
コメントを書く