React Conditional Rendering

Show different UI based on conditions.

✍️ 3 exercises + code challenge in this lesson

Use normal JavaScript to decide what to render:

  • if statements before the return.
  • The ternary operator inside JSX: {isLoggedIn ? <Logout /> : <Login />}
  • && to render something only when true: {count > 0 && <Badge />}
Careful with && and numbers: {0 && <X />} renders "0". Use count > 0 && ....

Key Takeaways: React Conditional Rendering

Mastering React Conditional Rendering helps you write clean and reliable React code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

React Conditional Rendering Code Example

React
<div id="root"></div>
<script src="https://unpkg.com/react@18.3.1/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.25.6/babel.min.js"></script>

<script type="text/babel">
const { useState, useEffect, useRef, useMemo, createContext, useContext } = React;
function Status({ stock }) {
  if (stock === 0) return <span style={{ color: "#DC2626" }}>Out of stock</span>;
  return <span style={{ color: "#16A34A" }}>{stock < 5 ? `Only ${stock} left!` : "In stock"}</span>;
}

function App() {
  const loggedIn = true;
  const unread = 3;

  return (
    <div>
      <p>{loggedIn ? "Welcome back!" : "Please sign in."}</p>
      {unread > 0 && <p>📬 You have {unread} new messages</p>}
      <p>Laptop: <Status stock={0} /></p>
      <p>Mouse: <Status stock={3} /></p>
      <p>Keyboard: <Status stock={40} /></p>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
</script>
Free sign-in required · Google login available

React Conditional Rendering Practice Exercises

Check what you learned in “React Conditional Rendering”.

/ 3 solved
Fill in the blank

Render the badge only when count is greater than 0.

{count > 0  <Badge />}
✓ Correct! Not quite. Try again.
Multiple choice

What does {0 && <X />} render?

✓ Correct! Not quite. Try again.
Code challenge

Render "Welcome back!" in a <p> when loggedIn is true, otherwise "Please sign in.".

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services