React / React Conditionals / Conditional Component Patterns
Home /React /React Conditionals /Conditional Component Patterns

Conditional Component Patterns

When a conditional pattern is reused across your app, the cleanest solution is to encapsulate it in a dedicated component. This is the React way of separating concerns.

Show / Hide Component

// Reusable Show component — cleaner than inline &&
function Show({ when, fallback = null, children }) {
  return when ? children : fallback;
}

// Usage
function App({ isLoggedIn, isAdmin }) {
  return (
    <div>
      <Show when={isLoggedIn} fallback={<LoginScreen />}>
        <Dashboard />
      </Show>

      <Show when={isAdmin}>
        <AdminPanel />
      </Show>
    </div>
  );
}

Guard Component:Role-Based Access

// Protects routes/components by required role
function ProtectedRoute({ user, requiredRole, children }) {
  if (!user) {
    return <Navigate to="/login" />;
  }
  if (user.role !== requiredRole) {
    return <p>🔒 You do not have permission to view this page.</p>;
  }
  return children;
}

// Usage in routing
<ProtectedRoute user={currentUser} requiredRole="admin">
  <AdminDashboard />
</ProtectedRoute>

Loading / Error / Empty State Pattern

function AsyncView({ loading, error, data, children }) {
  if (loading) return <Spinner />;
  if (error)   return <ErrorMessage message={error} />;
  if (!data)   return <EmptyState />;
  return {children};
}

// Usage — clean parent component
function CoursePage() {
  const { data, loading, error } = useCourses();
  return (
    <AsyncView loading={loading} error={error} data={data}>
      <CourseList courses={data} />
    </AsyncView>
  );
}