1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ReactにおけるCSSの設計手法

Posted at

ReactアプリケーションにおけるCSS設計のアウトプットとして記事を書きます

CSS Modules

CSS ModulesはCSSのスコープをコンポーネント単位で限定し、クラス名の衝突を防ぐことができます。

/* Button.module.css */
.button {
  background-color: blue;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
}
import styles from './Button.module.css';

function Button() {
  return <button className={styles.button}>Click me</button>;
}

Styled Components

Styled ComponentsはJavaScript内でCSSを記述できるライブラリで、動的なスタイリングが可能です。

import styled from 'styled-components';

const Button = styled.button`
  background-color: blue;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
`;

export default function App() {
  return <Button>Click me</Button>;
}

Next.jsでのCSS設計

Next.jsでは、CSS ModulesやStyled Componentsに加え、以下のような方法も一般的です。

グローバルCSS

Next.jsでは、グローバルスタイルを _app.js 内でインポートできます。

// pages/_app.js
import '../styles/globals.css';

export default function App({ Component, pageProps }) {
  return <Component {...pageProps} />;
}

内蔵のCSSサポート(CSS Modules)

Next.jsはデフォルトでCSS Modulesをサポートしています。

// components/Button.js
import styles from '../styles/Button.module.css';

export default function Button() {
  return <button className={styles.button}>Click me</button>;
}

プロジェクト規模ごとの使い分け

小規模プロジェクト

シンプルな構成を保つため、グローバルCSSやCSS Modulesが適しています。

中規模プロジェクト

コンポーネントごとにスタイルを分けられるCSS ModulesやStyled Componentsを推奨します。

大規模プロジェクト

テーマやデザインシステムとの連携が容易なStyled Componentsや、複数のCSS設計手法を組み合わせたハイブリッドな手法が適しています。

効果的なCSS設計のポイント

・コンポーネント単位でスタイルを管理することで、再利用性を向上させる

・明確な命名規則を使用することで、他の開発者との協力が容易になる

・テーマや変数を活用して一貫性のあるデザインを維持する

レスポンシブデザインの実践例

メディアクエリを利用してレスポンシブデザインを実現します。

.button {
  background-color: blue;
  padding: 10px 20px;
}

@media (max-width: 600px) {
  .button {
    padding: 5px 10px;
  }
}
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?