CodeBlanks Logo Icon CodeBlanks

Array to components

Learn to produce custom components from an array of data.

Components from arrays

Inside map you can call not only JSX tags but also your own component. Each item then becomes a rich card, row or cell.

Example: {items.map(i => <Product item={i} />)}. Product is your component; it receives the data through the item prop.

Because the component name starts with a capital letter, React treats it as a component, not a tag.

Data flow with props

When you split the list into a child component, you pass the data as a prop. The parent calls map; the child draws a single item.

This split makes the code easier to read and lets you reuse the child elsewhere. Each child has a single responsibility.

The key always goes on the outermost call: <Product key={i.id} item={i} />.

Practice ProductList component

Complete the skeleton. Write a ProductList component. The items array has id and name on each item. With .map() turn each item into <li key={item.id}><Product item={item} /></li>. Export it.

Starter code

App.jsx
// Define ProductList here

Sample solution

App.jsx
function ProductList() {
  const items = [{ id: 1, name: "Pen" }, { id: 2, name: "Book" }];
  return <ul>{items.map(item => <li key={item.id}><Product item={item} /></li>)}</ul>;
}

export default ProductList;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which of these is called as a component?

App.jsx
Component names always start with a capital letter.
  • <div>
  • <li>
  • <product>
  • <Product> Correct answer

Explanation: Capital letter means it is a component.

2 Array to components: fill in the missing part

Question
{items.map(item => <Product item={____} />)}
Answer
{items.map(item => <Product item={item} />)}

Explanation: You passed the item prop to Product.

3 Array to components: match the terms

Term Meaning
Component name Capital letter
Prop name Lowercase
children Content
map Loops over items

All lessons in Beginner