Course contentsShow
← React
Lesson 131 of 2,3964. Conditional Rendering in JSXFree lesson

Object Lookup Patterns for Mapping

Replace long if/else chains or switches with object lookups when mapping values to components or content.

Object Lookup Patterns for Mapping

What you'll learn: How to replace messy if/else chains or switch statements with clean object lookups when mapping values to components or content.


The Problem with Long Conditionals

When you need to show different components or content based on a value (like a status, type, or category), you might reach for if/else chains or switch statements inside IIFEs. These work, but they get verbose and hard to scan when you have many cases.

The Object Lookup Solution

Instead of checking conditions one by one, create an object where the keys match your possible values and the values are what you want to render. Then simply look up the key.

Before (Switch in IIFE):

{(() => {
  switch (status) {
    case 'loading': return <Spinner />;
    case 'error': return <ErrorMessage />;
    case 'success': return <DataDisplay />;
    default: return <Empty />;
  }
})()}

After (Object Lookup):

{
  {
    loading: <Spinner />,
    error: <ErrorMessage />,
    success: <DataDisplay />
  }[status] || <Empty />
}

The Analogy

Think of it like a filing cabinet. Instead of opening each drawer to check if it's the right one (if/else), you go directly to the labeled drawer (object key). The || <Empty /> pattern handles unknown keys like a "miscellaneous" drawer.

When to Use It

  • Mapping status/type strings to components
  • Icon selection based on category
  • Color/style variants
  • Any time you're choosing from a fixed set of options

Key Takeaway: Object lookups eliminate repetitive conditional logic by treating your mapping as data. Use them when you have a clear set of known values to map—your code becomes a simple dictionary lookup instead of a decision tree.