How do you conditionally render one of several possible components cleanly, without a long chain of if statements?
Short answer
When there are many possible cases, a lookup object mapping each case to a component is often cleaner and easier to read than a long chain of if or else if statements, and it also makes it simple to add new cases later without touching the existing logic.
Advertisement
AModel answer
When there are many possible cases, a lookup object mapping each case to a component is often cleaner and easier to read than a long chain of if or else if statements, and it also makes it simple to add new cases later without touching the existing logic.
const statusComponents = {
loading: <Spinner />,
error: <ErrorMessage />,
success: <ResultsList />,
};
function StatusView({ status }) {
return statusComponents[status] || null;
}Real-world example
A file upload component uses a lookup object to display a spinner, an error message, or the final result, instead of writing a long chain of if else statements that would only get harder to maintain over time.
Likely follow-ups
- What is the risk if the status value does not match any key in the lookup object?
- When would a switch statement still be a better choice than a lookup object?
Related topics