पाठ 6 / 25

Lists, Keys and Conditional Rendering

map, filter, &&, ternaries.

Render collections and choices

Render lists with array.map(), giving each item a stable, unique key (an id from your data, not the array index when items can be reordered, inserted or deleted). Keys let React match items between renders. For conditions use the ternary operator, && for "render this or nothing", or early returns for whole alternative outputs. Be careful with && and numbers: {count && <Badge />} renders "0" when count is 0.

Filtering, keys and an empty state, run

I ran this with React 19.3 and react-dom 19.3 on Node.js 22, compiling JSX with esbuild 0.28. Browser-style examples use jsdom 29 as a fake DOM (imported from a small setup-dom.mjs file) and act() to apply updates. The same TaskList renders two items, one item when completed tasks are hidden, and a "Nothing to do" message when the list is empty, using filter, map with keys and an early return.

import { renderToStaticMarkup } from "react-dom/server";

function TaskList({ tasks, showDone }) {
  const visible = showDone ? tasks : tasks.filter(t => !t.done);
  if (visible.length === 0) return <p>Nothing to do</p>;
  return (
    <ul>
      {visible.map(t => (
        <li key={t.id}>{t.title}{t.done ? " (done)" : ""}</li>
      ))}
    </ul>
  );
}
const tasks = [{ id: 1, title: "Write tests", done: true }, { id: 2, title: "Fix bug", done: false }];
console.log(renderToStaticMarkup(<TaskList tasks={tasks} showDone={true} />));
console.log(renderToStaticMarkup(<TaskList tasks={tasks} showDone={false} />));
console.log(renderToStaticMarkup(<TaskList tasks={[]} showDone={true} />));

Output:

<ul><li>Write tests (done)</li><li>Fix bug</li></ul>
<ul><li>Fix bug</li></ul>
<p>Nothing to do</p>

Use data ids as keys

Array indexes as keys cause wrong state to stick to the wrong row when items are reordered or removed.

त्वरित जाँच: What should you use as the key for list items fetched from an API?

  • The item's text length
  • Math.random()
  • Always the array index
  • A stable unique id from the data
Answer

A stable unique id from the data — Stable identity across renders.