Have you ever seen your React code turn into a wall of if
, switch
, or nested ternary operators?
There’s a simple pattern that makes it much cleaner: Object Lookup Pattern (also known as Object Map Pattern).
Final Result
😖 Before (the “traditional” way)
Let’s say you have several types of alerts and you want to render a different component for each type:
import SuccessAlert from "./SuccessAlert";
import ErrorAlert from "./ErrorAlert";
import InfoAlert from "./InfoAlert";
export default function App({ alertType }) {
if (alertType === "success") {
return <SuccessAlert />;
} else if (alertType === "error") {
return <ErrorAlert />;
} else if (alertType === "info") {
return <InfoAlert />;
} else {
return <p>Unknown alert type</p>;
}
}
The problem is: the more cases you add, the more ifs or else ifs pile up.
This makes the code harder to maintain and less readable.
✅ After (using the Object Lookup Pattern)
import SuccessAlert from "./SuccessAlert";
import ErrorAlert from "./ErrorAlert";
import InfoAlert from "./InfoAlert";
const alertMap = {
success: <SuccessAlert />,
error: <ErrorAlert />,
info: <InfoAlert />,
};
export default function App({ alertType }) {
return (
<div>
{alertMap[alertType] || <p>Unknown alert type Tchaaaca</p>}
</div>
);
}
🚀 Advantages
- Less repetitive code.
- Easy to add new cases (just add them to the object).
- More readable and straightforward.
📌 Bonus Tip
This pattern also works great for functions:
const operationMap = {
sum: (a, b) => a + b,
multiply: (a, b) => a * b,
};
console.log(operationMap["sum"](2, 3)); // 5
console.log(operationMap["multiply"](2, 3)); // 6
💬 Have you used this pattern in your projects?
It’s a lifesaver when your code starts to get full of conditionals.
Top comments (0)