propsでコンポーネントを再利用する

Reactでは、1つのコンポーネントを複数の場所で再利用できるように設計することが、保守性と拡張性の高いUI開発の鍵となります。

このドキュメントでは、TypeScript(TSX)ベースで「子コンポーネントを再利用するための基本的・柔軟なパターン」を紹介します。


1. 単純な再利用

type Props = {
  label: string;
};

const Button = ({ label }: Props) => {
  return 
<button>{label}</button>;
};

const App = () => {
  return (
    <>
      <Button label="保存" />
      <Button label="キャンセル" />
    </>
  );
};
  • 必要な情報(label)だけをpropsで渡すことで、シンプルに再利用できます。

2. childrenを活用した汎用構造

type Props = {
  children: React.ReactNode;
};

const Card = ({ children }: Props) => {
  return <div className="card">{children}</div>;
};

const App = () => {
  return (
    <>

<Card>

<h2>ユーザー情報</h2>

<p>氏名:Taro</p>
      </Card>

<Card>

<h2>お知らせ</h2>

<ul>

<li>更新1</li>

<li>更新2</li>
        </ul>
      </Card>
    </>
  );
};
  • childrenを使えば、汎用的なラッパーコンポーネントとしてあらゆる中身に対応可能です。

3. スロット的なprops構成(部分的に差し替え可能にする)

type Props = {
  header: React.ReactNode;
  content: React.ReactNode;
  footer?: React.ReactNode;
};

const Panel = ({ header, content, footer }: Props) => {
  return (
    <div className="panel">
      <div className="header">{header}</div>
      <div className="body">{content}</div>
      {footer && <div className="footer">{footer}</div>}
    </div>
  );
};

const App = () => {
  return (
    <Panel
      header={
<h1>タイトル</h1>}
      content={
<p>メインの本文です</p>}
      footer={
<small>© 2025 Example Inc.</small>}
    />
  );
};
  • それぞれのセクションをpropsで柔軟に差し替え可能なパターン。
  • 複数のUI構成を1つの再利用可能なコンポーネントで表現できます。

4. 共通のレイアウトにpropsで差分を与える

type Props = {
  icon: React.ReactNode;
  label: string;
};

const IconLabel = ({ icon, label }: Props) => {
  return (
    <div className="icon-label">
      {icon}

<span>{label}</span>
    </div>
  );
};

const App = () => {
  return (
    <>
      <IconLabel icon={<img src="/home.svg" />} label="ホーム" />
      <IconLabel icon={<img src="/user.svg" />} label="プロフィール" />
    </>
  );
};
  • アイコン付きテキストといったUIのバリエーション違いを、1つの汎用コンポーネントでまとめられます。

5. コンポーネントの配列でループして表示

const Item = ({ name }: { name: string }) => {
  return 
<li>{name}</li>;
};

const App = () => {
  const items = ["Apple", "Banana", "Grape"];
  return (

<ul>
      {items.map((item) => (
        <Item key={item} name={item} />
      ))}
    </ul>
  );
};
  • 子コンポーネントをループで使い回すことで、リスト表示やデータレンダリングに活用できます。

これらのパターンを組み合わせることで、保守性が高く、拡張にも強いコンポーネント設計が可能になります。

コメントを残す 0

Your email address will not be published. Required fields are marked *