Conditional Rendering

📘 React.js 👁 64 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

Conditional rendering allows you to display different UI elements based on certain conditions, such as state, props, or user actions.


Why Conditional Rendering?

  • Show or hide components

  • Display loading states

  • Handle authentication logic

  • Render content based on user input


1. Using if Statements

function Message({ isLoggedIn }) { if (isLoggedIn) { return <h1>Welcome Back</h1>; } return <h1>Please Log In</h1>; }

2. Using Ternary Operator

Best for simple conditions.

function Status({ isOnline }) { return ( <p>{isOnline ? "Online" : "Offline"}</p> ); }

3. Logical AND (&&) Operator

Used when you want to render something only if a condition is true.

function Notification({ hasMessage }) { return ( <div> {hasMessage && <p>You have a new message</p>} </div> ); }

4. Conditional Rendering with State

function ToggleMessage() { const [show, setShow] = React.useState(false); return ( <> <button onClick={() => setShow(!show)}> Toggle </button> {show && <p>Hello React</p>} </> ); }

5. Using switch Statement

Useful for multiple conditions.

function UserStatus({ status }) { switch (status) { case "loading": return <p>Loading...</p>; case "success": return <p>Success</p>; case "error": return <p>Error</p>; default: return null; } }

6. Preventing Rendering (null)

function Warning({ show }) { if (!show) return null; return <p>Warning Message</p>; }

Best Practices

  • Keep conditions simple

  • Avoid deeply nested ternaries

  • Use meaningful variable names

  • Extract complex logic into functions or components


Common Use Cases

  • Authentication checks

  • Loading spinners

  • Error messages

  • Feature toggles


Key Points

  • Conditional rendering works like JavaScript conditions

  • Use if, ternary, &&, or switch

  • null prevents rendering

  • Helps build dynamic UIs


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes

🤖 AI Quizer Assistant

📝 Quiz
📚 Categories
🏆 Leaderboard
📊 My Score
❓ Help
👋 Hi! I'm your AI quiz assistant for Quizer.in!

I can help you with:
• 📝 Finding quizzes
• 🏆 Checking leaderboard
• 📊 Your performance stats

Type 'help' to get started! 🚀
AI is thinking...