Course contentsShow
← Web Development
Lesson 1630 of 2,98230. Web Authorization PatternsFree lesson

Conditional Rendering Based on Roles

Implement conditional rendering to show or hide UI elements based on user roles using JavaScript logic.

Conditional Rendering Based on Roles

What you'll learn: How to dynamically show or hide UI elements based on a user's role using simple JavaScript logic.

Now that you know how to store user roles in the frontend, it's time to put that information to work. Conditional rendering means your application displays different interface elements depending on who's logged in—like showing an "Admin Dashboard" link only to admins, or hiding a "Delete" button from regular users.

The Core Idea

Think of conditional rendering like a bouncer at different club areas. Not everyone gets into the VIP section—the bouncer checks your wristband (role) before letting you through. Similarly, your UI checks the user's role before rendering certain components.

The pattern is straightforward: retrieve the user's role from wherever you stored it (localStorage, memory, decoded JWT payload), then use JavaScript conditional logic to decide what to render.

Basic Implementation Pattern

// Assume you've retrieved the user role
const userRole = localStorage.getItem('userRole'); // e.g., 'admin', 'user', 'guest'

// Conditional rendering with vanilla JavaScript
const adminPanel = document.getElementById('admin-panel');
if (userRole === 'admin') {
  adminPanel.style.display = 'block';
} else {
  adminPanel.style.display = 'none';
}

// Or conditionally add elements
if (userRole === 'admin' || userRole === 'moderator') {
  const deleteButton = document.createElement('button');
  deleteButton.textContent = 'Delete Post';
  document.getElementById('actions').appendChild(deleteButton);
}

You can also create reusable helper functions:

function canUserAccess(requiredRole) {
  const userRole = localStorage.getItem('userRole');
  return userRole === requiredRole;
}

if (canUserAccess('admin')) {
  // Render admin-only features
}

Key Takeaway: Conditional rendering uses simple JavaScript logic to show or hide UI elements based on stored user roles, creating a personalized interface for different permission levels.