- Home
- /
- Tutorials
- /
- React Tutorial
- /
- Conditional Rendering
Conditional Rendering
Conditional Rendering
There is no
ifinside JSX, because JSX takes expressions. Every technique here is a way of producing a value that is either some UI or nothing.
The three tools
Almost all conditional React is one of three shapes, and picking the right one is mostly about how many branches you have.
- Early return - the whole component renders something different, or nothing.
- Ternary - two alternatives in one spot.
&&- one thing or nothing.
All three, in one component
jsx
function Status({ state, count }) {
// 1. Early return: nothing to show at all.
if (state === "hidden") return null
return (
<div>
{/* 2. Ternary: one of two things */}
<p>{state === "busy" ? "Working…" : "Ready"}</p>
{/* 3. && : something or nothing */}
{count > 0 && <p>{count} pending</p>}
</div>
)
}
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(
<div>
<Status state="busy" count={3} />
<Status state="ready" count={0} />
<Status state="hidden" count={9} />
<p style={{ color: "#64748b" }}>Three renders above; the third produced nothing.</p>
</div>
)