Coding for All
Lesson 5: Lists with map
Lists with map Turn an array of data into a list on screen.
1function App() {
2 const toppings = ['Cheese', 'Mushroom', 'Olive'];
3 return (
4 <ul>
5 {toppings.map(t => <li key={t}>{t}</li>)}
6 </ul>
7 );
8}
9export default App;
Terminal
$ npm run dev
VITE v5.4 ready in 312 ms
Local: http://localhost:5173/
(your app is live: look at the browser window above!)
Every line, explained
function App() {
The App component: every lesson's page starts from this function.
const toppings = ['Cheese', 'Mushroom', 'Olive'];
The data: a plain JavaScript array. In a real app this list would come from a server (the Spring Boot course on this site builds exactly that kind of /menu endpoint!).
return (
When JSX spans several lines, it goes inside round brackets after return. The brackets keep the JSX attached to the return: without them, JavaScript would think the return finished at the end of that line and hand back nothing.
<ul>
<ul> is an unordered list: the tag that draws bullet points.
{toppings.map(t => <li key={t}>{t}</li>)}
The most React line there is. Curly braces drop into JavaScript, and map is a built-in array tool: it runs a little arrow function on each item (t is the topping it is currently holding) and collects the results. Three strings in, three <li> list item tags out. The key={t} gives each item a label of its own; React uses keys to keep track of list items when the data changes.
</ul>
Close the list.
);
The ); closes the return's round bracket.
}
This } closes the component function.
export default App;
export default App hands your component to the rest of the app. A locked line in every lesson: the app's starter file (main.jsx) imports App and mounts it on the page.