2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【React】条件付きレンダリングとは

2
Posted at

条件付きレンダリングとは

Reactにおける「条件付きレンダリング」とは、ある条件が満たされた場合にのみ特定の要素やコンポーネントをレンダリングすることを指します。これにより、動的なUIを作成し、特定の状況に応じて異なるコンポーネントや要素を表示することができます。

条件付きレンダリングを実現する方法にはいくつかのアプローチがありますが、一般的な方法のいくつかを以下に示します。

使用方法

1. 条件付き演算子(Ternary Operator)を使用する:

function MyComponent({ isLoggedIn }) {
  return (
    <div>
      {isLoggedIn ? <p>Welcome, user!</p> : <p>Please log in.</p>}
    </div>
  );
}

2. 論理 && 演算子を使用する:

function MyComponent({ isLoggedIn }) {
  return (
    <div>
      {isLoggedIn && <p>Welcome, user!</p>}
    </div>
  );
}

3. 条件付きレンダリングを行うための関数を作成する:

function MyComponent({ isLoggedIn }) {
  const renderWelcomeMessage = () => {
    if (isLoggedIn) {
      return <p>Welcome, user!</p>;
    } else {
      return <p>Please log in.</p>;
    }
  };

  return (
    <div>
      {renderWelcomeMessage()}
    </div>
  );
}

まとめ

これらの方法を使用すると、特定の条件が満たされた場合にのみコンポーネントや要素がレンダリングされるように制御できます。条件付きレンダリングは、ユーザーの認証状態やアプリケーションの状態に基づいて動的なUIを作成するために広く使用されます。

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?