← Back to Chapters

Conditional Components

⚛️ Conditional Components

? Quick Overview

In React, conditional components are small, reusable components that render different UI based on props or logic. Instead of putting many if or ternary expressions directly inside a big component, you extract those conditions into focused child components.

This approach improves readability, maintainability, and separation of concerns, making your UI logic easier to understand and test.

✨ Idea: Turn conditions into components!

? Key Concepts

  • Conditional Component: A component whose rendering depends on props or state.
  • Separation of Concerns: Each condition gets its own component (e.g., LoggedIn, LoggedOut).
  • Parent Chooser: A parent component decides which child component to render.
  • Role / Permission Based UI: Different components for admins, users, guests, etc.
  • Wrapper / Guard Components: Components like Protected decide whether to render children.
  • Prop-Driven Styling: Components like Alert change style based on props.

? Syntax & Theory

A typical pattern for conditional components is:

  1. Create small components for each visual state (e.g., success, error, empty).
  2. Use a parent component to decide which one to render based on props or state.
  3. Optionally, create wrapper components that guard content (authentication, permissions, feature flags).

Conceptually:

? View Code Example
// Pattern: parent chooses which conditional component to render
function StateA() {
return <p>State A UI</p>;
}

function StateB() {
return <p>State B UI</p>;
}

function Parent({ condition }) {
return condition ? <StateA /> : <StateB />;
}

? Example: Login Flow Components

Here, we create two small components for different user states and let the parent component decide which one to render:

? View Code Example
// Renders different messages depending on whether the user is logged in
function LoggedIn() {
return <h4 className="text-success">Welcome back, user! ?</h4>;
}

function LoggedOut() {
return <h4 className="text-danger">Please log in to continue.</h4>;
}

function LoginControl({ isLoggedIn }) {
return isLoggedIn ? <LoggedIn /> : <LoggedOut />;
}

? Live Output / Explanation

If you call <LoginControl isLoggedIn={true} />, React will render the <LoggedIn /> component and show a green welcome message.

If you pass isLoggedIn={false}, React will render <LoggedOut /> and show a red “Please log in” message instead.

The parent LoginControl is responsible only for choosing which component to display, making the logic easy to read and maintain.

? Example: Role-Based Components

Conditional components are ideal for handling role-based or permission-based rendering:

? View Code Example
// Shows a different dashboard depending on the user's role
function AdminPanel() {
return <div className="border p-3">Admin Dashboard ?️</div>;
}

function UserPanel() {
return <div className="border p-3">User Dashboard ?</div>;
}

function Dashboard({ role }) {
switch (role) {
case "admin":
return <AdminPanel />;
case "user":
return <UserPanel />;
default:
return <p>Access Denied ❌</p>;
}
}

? Live Output / Explanation

For <Dashboard role="admin" />, the admin dashboard appears. For <Dashboard role="user" />, the user dashboard appears. Any other value shows Access Denied ❌.

Adding a new role is as simple as creating a new component (for example, ManagerPanel) and extending the switch statement.

?️ Example: Conditional Wrapper (Protected)

You can also create wrapper components that only render their children when a condition is met, such as authentication:

? View Code Example
// Wrapper that protects its children behind an authentication check
function Protected({ isAuthenticated, children }) {
if (!isAuthenticated) return <p className="text-danger">Login required!</p>;
return children;
}

function App() {
const isLoggedIn = true;

return (
<Protected isAuthenticated={isLoggedIn}>
<h4>Welcome to your dashboard! ?</h4>
</Protected>
);
}

? Live Output / Explanation

If isAuthenticated is false, the user sees Login required!. If it is true, the wrapped dashboard content is rendered.

This pattern is extremely useful for protecting routes, hiding content, or conditionally wrapping entire sections of the UI based on a central rule.

? Example: Conditional Styling Component

Components can decide styling or structure based on props as well:

? View Code Example
// Reusable alert component that chooses a CSS class based on the type
function Alert({ type, message }) {
const alertClass =
type === "success"
? "alert alert-success"
: type === "error"
? "alert alert-danger"
: "alert alert-warning";

return <div className={alertClass}>{message}</div>;
}

// Usage:
<Alert type="success" message="Data saved successfully!" />

? Live Output / Explanation

Passing different type values (like "success", "error", "warning") changes the CSS class and therefore the visual style of the alert, while the core component remains the same.

This makes your components highly reusable with dynamic behavior controlled entirely by props.

⚙️ Benefits of Conditional Components

  • ✅ Cleaner JSX — no deeply nested if or ternary blocks cluttering logic.
  • ✅ Reusable building blocks that can be combined flexibly across pages.
  • ✅ Easier testing and debugging — each condition has its own small component.
  • ✅ Improved scalability — adding new conditions means adding new components, not new branches everywhere.
  • ✅ Better naming and semantics — components like GuestView or EmptyState are self-explanatory.

? Real-World Use Cases

  • Authentication and permission-based UI control (admin vs user vs guest).
  • Dynamic layouts (mobile vs desktop views, different dashboards per role).
  • Feature toggles or A/B testing scenarios.
  • Conditional forms, modals, loaders, and alerts.
  • Empty states and error states (e.g., NoData, ErrorScreen components).

? Tips & Best Practices

  • Split UI logic into small conditional components rather than long JSX blocks.
  • Use descriptive names like GuestView, AdminPanel, or EmptyState.
  • Combine with return null in components that sometimes should render nothing.
  • Keep parent components focused on choosing what to render, not on how each state looks.
  • Group related conditional components in the same file or folder for easier maintenance.

? Try It Yourself

  1. Create GuestView and MemberView components, and render them conditionally in a parent component.
  2. Build a Protected component that shows its children only if a user is logged in.
  3. Design an Alert component that changes color based on the alert type (success, error, info).
  4. Refactor an existing component with multiple if statements into multiple smaller conditional components.
  5. Implement a RoleSwitcher that renders different layout components based on a role prop.

Goal: Learn how to simplify complex UI logic by breaking it into conditional components that render different outputs cleanly and maintainably.