N
N
Nick82017-01-26 18:57:09
JavaScript
Nick8, 2017-01-26 18:57:09

How to generate dynamic number of components in React?

For example, I received data from the server and I need to generate several product components, passing their own props to each. How can I do that?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Gushchin, 2017-01-26
@Nick8

Make an ItemsList and Item component:

class Item extends React.PureComponent {
  render() {
    const { name, color } = this.props

    return (
      <li>
         <b>{name} ({color})</b>
      </li>
    )
  }
}


class ItemsList extends React.PureComponent {
  render() {
    const { items } = this.props

    return (
      <ul>
        {items.map(item => (
          <Item key={item.id} {...item} />
        )}
      </ul>
    )
  }
}

Pay attention to the key property here - it is necessary when you use dynamic children.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question