Conditional Rendering
React mein, conditional rendering ka matlab hai component ke andar kuch elements ko render karna ya nahi karna specific conditions ke basis par. Yeh concept JavaScript ke conditional statements jaisa hi hota hai.
Conditional Rendering ke Techniques
Conditional rendering ko achieve karne ke liye React mein kai techniques use hoti hain:
- if Statement
- Ternary Operator
- Logical && Operator
- Switch Statement (Rare cases)
1. if Statement
if
statement ko use karke aap conditions ke basis par elements ko render kar sakte hain.
Example:
Is example mein, Greeting
component isLoggedIn
prop ke basis par decide karta hai ki kaunsa message display karna hai.
2. Ternary Operator
Ternary operator ek concise tarika hai conditional rendering karne ka. Yeh ek inline if-else statement jaisa hota hai.
Example:
Is example mein, ternary operator (condition ? true : false
) use karke conditional rendering ki gayi hai.
3. Logical && Operator
Logical &&
operator ko use karke aap conditionally elements ko render kar sakte hain. Agar condition true hai to element render hoga, agar false hai to render nahi hoga.
Example:
Is example mein, agar unreadMessages.length
greater than 0 hai to h2
element render hoga.
4. Switch Statement
Rare cases mein aap switch
statement ka use bhi kar sakte hain jab aapko multiple conditions ko handle karna ho.
Example:
Is example mein, switch
statement ko use karke different statuses ke basis par different messages display kiye gaye hain.
Conclusion
React mein conditional rendering ka use karke aap dynamic aur responsive UI bana sakte hain jo user input ya application state ke basis par change hota hai. if
statement, ternary operator, logical &&
operator, aur switch
statement jaise techniques ka use karke aap complex rendering logic ko easily manage kar sakte hain.