While the same ternary, &&, and if/else techniques used for conditionally rendering small pieces of markup apply equally to swapping entire components, this pattern deserves its own attention once there are more than two possible states to represent, like loading/error/success, or several different role-based views of the same page — at that point, an if/else chain, a switch statement mapping each state to its component, or even a lookup object keyed by state name, generally reads far more clearly than a chain of nested ternaries or &&s crammed into the JSX.
1Understanding Conditional Component Rendering
While the same ternary, &&, and if/else techniques used for conditionally rendering small pieces of markup apply equally to swapping entire components, this pattern deserves its own attention once there are more than two possible states to represent, like loading/error/success, or several different role-based views of the same page — at that point, an if/else chain, a switch statement mapping each state to its component, or even a lookup object keyed by state name, generally reads far more clearly than a chain of nested ternaries or &&s crammed into the JSX.
Once you're choosing between three or more entire components based on some state value, a switch statement or a plain lookup object mapping each state to its component is almost always more readable than a chain of nested ternaries.
function Page({ status }) {
if (status === 'loading') return <Spinner />;
if (status === 'error') return <ErrorMessage />;
return <Content />;
}2Practical Example
Here is a real-world application of Conditional Component Rendering showing how it is used in production React code.
const views = {
loading: Spinner,
error: ErrorMessage,
success: Content
};
function Page({ status }) {
const View = views[status] ?? Content;
return <View />;
}3Best Practices
Follow these guidelines when working with Conditional Component Rendering:
1. Use a switch statement, or a plain object mapping state values to components, once there are three or more entire components to choose between, rather than a chain of nested ternaries
2. Keep each conditionally-rendered branch as its own separate, named component, so the top-level conditional logic reads clearly as a simple dispatch rather than mixing layout details into the condition itself
3. Compute which component to render into a variable before the return statement for anything beyond the simplest single ternary, keeping the actual JSX return statement clean and readable
Tip: Once you're choosing between three or more entire components based on some state value, a switch statement or a plain lookup object mapping each state to its component is almost always more readable than a chain of nested ternaries.
function Page({ status }) {
if (status === 'loading') return <Spinner />;
if (status === 'error') return <ErrorMessage />;
return <Content />;
}