In React you don't manipulate the DOM to show and hide things — you describe what the UI should look like for the current data, and React reconciles the difference. This chapter collects the idioms for that: conditional rendering, lists, fragments and composition.
Conditional rendering
JSX is JavaScript, so you render conditionally with ordinary expressions:
{isLoggedIn && <Dashboard />} // render when true{isLoggedIn ? <Dashboard /> : <Login />} // either/or{error && <p className="error">{error}</p>} // guard// Early return for whole-component branchesfunction Page({ loading, data }) {if (loading) return <Spinner />;if (!data) return <Empty />;return <Content data={data} />;}
Lists & keys, revisited
map turns data into elements. The key must be stable and unique so React can track items across renders — always a real id, never the array index for dynamic lists:
function ProgrammeList({ programmes }) {if (programmes.length === 0) return <p>No programmes yet.</p>;return (<ul>{programmes.map(p => (<li key={p.id}>{p.name} — {p.fee}</li>))}</ul>);}
Fragments
A component must return one root element. When you don't want an extra wrapper <div>, use a Fragment (<>…</>) — it groups children without adding a DOM node:
function Row() {return (<><td>Aanya</td><td>₹8 LPA</td></>);}// Use <React.Fragment key={id}> when a fragment needs a key in a list.
Composition with children
Prefer composition over configuration — pass JSX through children (and named "slot" props) to build flexible, reusable components rather than adding endless boolean props:
function Card({ title, children, footer }) {return (<div className="card"><h3>{title}</h3><div className="body">{children}</div>{footer && <div className="footer">{footer}</div>}</div>);}<Card title="Data Analytics" footer={<Button>Enrol</Button>}><p>A 6-month, job-ready programme.</p></Card>
Practice
Build a ProgrammeList that shows an empty state when there's nothing, maps items with real keys, and renders a "Featured" badge only for flagged items (mind the && gotcha). Then make a reusable Card using children and a footer slot.
Key takeaways
- 01Render conditionally with && , the ternary, or an early return — describe the UI, don't mutate the DOM.
- 02Beware {count && …} — a 0 renders; use {count > 0 && …}.
- 03map data to elements with a stable, unique key (a real id, not the index).
- 04Fragments (<>…</>) group children without an extra wrapper element.
- 05Favour composition via children and slot props over piling on configuration props.
