From an Array to a List

A festival app is full of lists: bands, stages, tickets. In the JavaScript course, you showed an array with a loop that created an li for each element and appended it to the page. In React, you don't create elements one by one. You turn the array of data into an array of JSX elements, and React shows them all.

You already know the method that does it: map(). It calls its function for each element and makes a new array of what the function returns. And the function can return JSX:

const stages = ["Main Stage", "Tent", "Forest Stage"];
const items = stages.map((stage) => <li>{stage}</li>);

items is an array of three elements: <li>Main Stage</li>, <li>Tent</li> and <li>Forest Stage</li>. When you put an array in curly braces in JSX, React shows its elements one after another. So you can write the map() right where the items should go:

const stages = ["Main Stage", "Tent", "Forest Stage"];

export default function App() {
    return (
        <ul>
            {stages.map((stage) => (
                <li>{stage}</li>
            ))}
        </ul>
    );
}

The page shows a list of the three stages. When the function's JSX is longer than one line, put it in parentheses, just as after return:

{stages.map((stage) => (
    <li>
        <strong>{stage}</strong>
    </li>
))}

The best part comes when the data changes. Add a stage to the array, and the list has one more item, without any change to the JSX. The page follows the data.

When you run the code, the console shows a warning from React: Each child in a list should have a unique "key" prop. The page works anyway. What React wants is in the next exercise.

Instructions

Show the bands from the array bands in the list ul: turn each name into an li with map().

Add Tin Robots to the end of the array. Its item appears at the end of the list, and the JSX stays as it is.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

1/11

Next