React Conditional Rendering
Conditionally rendering components and elements
If Statement
if (isLoggedIn) {
return <Dashboard />;
}
return <Login />;
Ternary Operator
{isLoggedIn ? <Dashboard /> : <Login />} # ternary
{count > 0 ? <p>{count}</p> : <p>Zero</p>}
Logical AND
{isLoggedIn && <Dashboard />} # render if true
{error && <p>{error}</p>} # show error if exists
Logical OR
{name || "Guest"} # default value
Switch Statement
const Component = () => {
switch (status) {
case 'loading': return <Loading />;
case 'error': return <Error />;
default: return <Content />;
}
};