Technology · React
React Conditional Rendering
Show or hide elements in React using if statements, ternaries, logical operators, and switch patterns.
TL;DR
- 01Use if statements to return different JSX based on conditions.
- 02Use ternary expressions inside JSX for inline conditionals.
- 03Use logical AND for simple show-or-hide patterns.
If Statements
- Return different JSX based on a condition before the return statement.
function UserInfo({ user }) { if (!user) return <p>Loading...</p>; return <div>{user.name}</div>; } - This is the clearest pattern when conditions are complex.
- Use early returns to handle edge cases at the top of the component.
- Combine multiple if statements for sequential checks.
- Avoid nesting too many ifs — extract sub-components instead.
Ternary Operator
- Use the ternary operator inside JSX for inline conditionals.
<div>{user ? user.name : "Guest"}</div> - Read as "if user is truthy, show user.name, else show Guest".
- Keep ternaries simple and readable — use if statements for complex logic.
- Nest ternaries only for quick reads, not for multiple conditions.
<div>{user ? (user.isAdmin ? "Admin" : "User") : "Guest"}</div> - Extract nested ternaries into separate components for clarity.
Logical AND Operator
- Use
&&to render JSX only when a condition is true.<div>{user && <p>Hello, {user.name}!</p>}</div> - This hides the element when the condition is false without rendering anything.
- Only use when there is no "else" case needed — otherwise use ternary.
- Beware of falsy values — avoid using
&&with0or empty strings.{count > 0 && <p>{count} items</p>} - Use ternary instead if you need to show something when the condition is false.
Switch Patterns
- Use a switch statement before the return for multiple conditions.
function Status({ status }) { switch (status) { case "loading": return <p>Loading...</p>; case "success": return <p>Done!</p>; case "error": return <p>Error occurred</p>; default: return null; } } - Switch works well when you have many distinct states to handle.
- Always include a default case for unexpected values.
- Extract each case into a separate component for reusability.
Conditional Components
- Create helper components to encapsulate conditional rendering logic.
function IfAdmin({ children, user }) { return user?.isAdmin ? children : null; } <IfAdmin user={user}> <AdminPanel /> </IfAdmin> - Use render props or children to control what is displayed.
- Name components clearly to show their conditional purpose.
- This pattern keeps components focused and testable.
- Combine with custom hooks for more complex conditional logic.
Tip: Prefer if statements and switch for clarity, since they separate logic from JSX and are easier to test and refactor.
Warning: Avoid using
&&with falsy values like0or empty strings, since they will render nothing instead of the string itself.