Conditional Rendering
Displaying different UI elements or components based on application state or props.
Mental Model
"The Toggle Switch: Flipping the wall switch changes whether the chandelier is illuminated or dark."
Interactive Engine Walkthrough
Off means the element is not in the tree at all — React never creates it.
Bump cleared in the feed, then turn the condition off and on. Under unmount you get a fresh instance and a counter back at 0; under hide nothing is thrown away.
Reference Code Snippet
1function AuthButton({ isLoggedIn }) {
2 // If true, render the Profile button
3 if (isLoggedIn) {
4 return <button>View Profile</button>;
5 }
6
7 // Otherwise, render the Login button
8 return <button>Log In</button>;
9}- 01.Use ternary operators (condition ? <A /> : <B />) for dual-branch rendering.
- 02.Use logical AND (condition && <Component />) for single-branch rendering.
- 03.Returning null from a component tells React to render nothing to the DOM.
01. Logic in the View
Since JSX is JavaScript, we don't need a special template syntax like `ng-if` or `v-if`. We use standard JS patterns. React treats `null`, `undefined`, and `false` as "empty," meaning nothing will be rendered to the screen.
Pattern Guide
- Early Return Full block change
- Ternary (?:) Switching between two nodes
- Logical (&&) Optional visibility
02. The Zero Trap
A common "gotcha" in React is that while `false` renders nothing, the number `0` **does** render. If you write `count && <UI />` and count is 0, React will render the number '0' on your screen. Always be explicit with boolean conversions: `!!count && <UI />`.
Maintainability Note
"If your ternary expressions are nesting (e.g. condition ? a : b ? c : d), stop immediately. Move that logic into a separate helper function or a sub-component to keep the JSX readable."