Render arrays with map
Turn records into visible rows
A React list is a group of elements derived from data. Instead of writing a separate list item for every museum exhibit, use JavaScript map to produce one element per record. Each record in these examples has a persistent ID. The key helps React match siblings when the data changes; the next lesson explains the details. Replace src/App.jsx in the approved Chapter 3 project with each independent example. Screen results are predicted, not browser-tested.
export default function App() { const exhibits = [ { id: 'm1', name: 'Moon map' }, { id: 'm2', name: 'Glass compass' }, { id: 'm3', name: 'River model' } ]; const rows = exhibits.map(exhibit => ( <li key={exhibit.id}>{exhibit.name}</li> )); return <main><h1>Exhibits</h1><ul>{rows}</ul></main>;}Expected: a heading and three list items in array order. The callback receives each object and returns one JSX element. The braces around rows insert the resulting array into the ul. The ul and li elements retain ordinary list semantics. Changing the data changes the rendered items without rewriting the surrounding structure.
Filter before mapping
function openExhibits(exhibits) { return exhibits.filter(exhibit => exhibit.open === true);}
function ExhibitList({ exhibits }) { const visible = openExhibits(exhibits); if (visible.length === 0) return <p>No open exhibits.</p>; return <ul>{visible.map(exhibit => ( <li key={exhibit.id}>{exhibit.name}</li> ))}</ul>;}
export default function App() { return <main> <h1>Open exhibits</h1> <ExhibitList exhibits={[ { id: 'm1', name: 'Moon map', open: true }, { id: 'm2', name: 'Glass compass', open: false }, { id: 'm3', name: 'River model', open: true } ]} /> <h2>After closing</h2> <ExhibitList exhibits={[]} /> </main>;}Expected: Moon map and River model in the first list, and No open exhibits under the second heading. Filtering creates a new array; it does not remove records from the original. This contract requires a boolean open property. A missing or nonboolean value is not counted as open. An empty successful dataset needs a useful message, as covered in Chapter 7.
Remember to return a row
export default function App() { const exhibits = [{ id: 'm1', name: 'Moon map' }]; const rows = exhibits.map(exhibit => { <li key={exhibit.id}>{exhibit.name}</li>; }); return <main><h1>Exhibits</h1><ul>{rows}</ul></main>;}Expected: the heading and an empty list. The arrow callback has a block body but no return, so its result is undefined. Correct it by writing return before the JSX or using a parenthesized expression as in the first example. Do not replace map with forEach: forEach does not return an array of transformed values.
Practice
Build a list of library rooms with stable IDs. Filter to rooms marked available, show the room names in source order, and show a useful message for an empty result. Test all available, none available and mixed data.