React Essentials — Components, JSX, Props, State & MoreEntry 9 of 11
Conditional Rendering and JSX in Variables
Choosing what to render based on state, using plain JavaScript.
Notes
JSX is a JavaScript expression, so it can be stored in a variable, returned from a function, or chosen with ordinary logic. Common patterns:
- Ternary
cond ? <A /> : <B />for either/or. - Logical AND
cond && <A />for show/hide. - Early return for whole-component guards.
- Variable: build the JSX with
ifstatements before thereturn, which keeps the markup clean.
What / Why / When
- What
Rendering different UI depending on state.
- Why
React has no template directives, so standard JavaScript does the job.
- When
Empty states, loading states, selected tabs, permissions.
- Use case
Show a "Please select a topic" message until a tab is chosen.
Code compare
import { useState } from "react";export function Examples() { const [selectedTopic, setSelectedTopic] = useState<Topic | null>(null); let tabContent = <p>Please select a topic.</p>; if (selectedTopic) { tabContent = ( <div id="tab-content"> <h3>{EXAMPLES[selectedTopic].title}</h3> <p>{EXAMPLES[selectedTopic].description}</p> </div> ); } return <section>{tabContent}</section>;}@if (selectedTopic(); as topic) {<div id="tab-content"> <h3>{{ examples[topic].title }}</h3> <p>{{ examples[topic].description }}</p></div>} @else {<p>Please select a topic.</p>}The closest thing to "JSX in a variable" is a named <ng-template>:
<ng-template #emptyState><p>Please select a topic.</p></ng-template><ng-container [ngTemplateOutlet]="emptyState" />Differences and gotchas
- Beware
{items.length && <List />}in React. When the length is0, React renders the number0. Useitems.length > 0 &&instead. - Angular uses built-in control flow (
@if,@else,@switch) rather than JavaScript expressions.@let(v18.1+) declares template-local variables.
Quick reference
| React | Angular |
|---|---|
cond ? <A /> : <B /> | @if (cond) { } @else { } |
cond && <A /> | @if (cond) { } |
switch in a helper | @switch / @case |
| JSX in a variable | <ng-template #ref> + ngTemplateOutlet |