17
1

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学習ログ No.10

Last updated at Posted at 2025-10-11

React公式ドキュメント学習メモ:条件付きレンダー

Reactコンポーネントで条件によって表示を切り替える際の、主要な4つの手法を比較

【共通タスク】 isVip が true の場合、名前に 👑 を追加

最小コードでの比較

1. ifreturn (早期リターン)

function UserCard({ name, isVip }) {
  // isVipなら、もうここで終わり
  if (isVip) {
    return <p>{name} 👑</p>;
  }
  // isVipでない場合のデフォルト
  return <p>{name}</p>;
}

2. 三項演算子 (? :)

function UserCard({ name, isVip }) {
  return (
    <p>
      {/* 👑を含めるか、含めないかの2択 */}
      {isVip ? `${name} 👑` : name}
    </p>
  );
}

3. 論理 AND (&&)

function UserCard({ name, isVip }) {
  return (
    <p>
      {name}
      {/* isVipのときだけ ' 👑' を追加 */}
      {isVip && ' 👑'}
    </p>
  );
}

4. if と変数

function UserCard({ name, isVip }) {
  let icon = ''; // まず空で宣言
  // 条件が満たされたら変数に値をセット
  if (isVip) {
    icon = ' 👑';
  }
  // 最終的なJSXで変数を使う
  return <p>{name}{icon}</p>;
}
17
1
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
17
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?