Show different UI based on conditions.
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
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