Conditional Rendering in React

 What is Conditional Rendering?

Conditional rendering in React means showing different UI elements based on a condition.

This works as a if else statement inside JSX.

Why conditional Rendering is important?

Conditional rendering is used in many real world situations, such as
 
  • Showing Login or Dashboard based on user login status
  • Showing Loading text while data is loading
  • Showing Error messages
  • Hiding or showing buttons
  • Displaying content based on user roles
Basic Example using Ternary Operator ( ?: )

The most common way to do conditional rendering in JSX is using the ternery operator.

Example: Login vs Dashboard



How this works?

isLoggedIn -> condition
if isLoggedIn is true -> <Dashboard/> is shown
if isLoggedIn is false ->  <Login/> is shown



Complete Component Example


If isLoggedIn is true, the Dashboard component will appear.
If it is false, the Login component will appear.

Using Conditional Rendering with Text


This is useful for dynamic messages.


Using && (AND) Operator

If you want to show something only when the condition is true, you can use the && operator



If isLoggedIn is true , shows the dashboard
If isLoggedIn is false nothing shows

This is commonly used for 
  • Notifications
  • Buttons
  • Optional UI elements

Example: Show Logout button only when logged in

Conditional Rendering with Loading State



This is very useful when working with APIs.

Using if else Outside JSX 

Sometimes JSX becomes messy. You can use if else before returning JSX.




This method is clean for larger conditions.

Real World Use Cases

  • Authentication systems
  • Protected routes
  • Admin dashboards
  • Profile pages

Commenly Mistakes to Avoid

❌ Using if directly inside JSX
✔ Use ternary or &&

❌ Forgetting to return JSX
✔ Always return a component or element

❌ Making JSX too complex
✔ Move logic outside JSX when needed











Comments

Popular posts from this blog

Styling React Applications in 2026

React Best Practices in 2026

Fetching Data in React Using APIs