Lists

I. Rendering arrays of React Elements

1. Using for loop

We can render multiple components at the same time using a for loop with JSX:

const elements = [] 
const array = [1,2,3,4,5]

for(let i = 0; i < array.length; i++){
   elements.push(<li>{array[i]}<li/>)
}

ReactDOM.render(
  <ol>{elements}</ol>,
  document.getElementById('root')
)

2. Using map() to render arrays of React Elements

We can use map() method to create an array of React Elements.

The map() method is called on an array and iterate over each item of the array and return a new version of each.

For example

const list =[
  {product:"Apple", price:3},
  {product:"Banana", price:1},
  {product:"Carrot", price:2},
  {product:"Donuts", price:5},
  {product:"Eggplant", price:4}
]

const elements = list.map( (item) => {
  return <li>Product: {item.product} | Price: ${item.price}  </li>
})

ReactDOM.render(
  <ol>{elements}</ol>,
  document.getElementById('root')
)

We can also use map() method directly inside a JSX expression:

ReactDOM.render(
  <ol>{
      list.map( (item) => 
          <li>Product: {item.product} | Price: ${item.price} </li>
      )}
  </ol>,
  document.getElementById('root')
)

II. Adding Keys to List Items

React uses Keys to help render list items quickly. It identifies which items have changed, are added, or are removed.

Keys should be a string that uniquely identifies a list item from the other items on the list, such as an ID attribute.

For example

const list =[
  {id: 1, product:"Apple", price:3},
  {id: 2, product:"Banana", price:1},
  {id: 3, product:"Carrot", price:2},
  {id: 4, product:"Donuts", price:5},
  {id: 5, product:"Eggplant", price:4}
]

const elements = list.map( (item) => {
  return <li key={item.id}>Product: {item.product} | Price: ${item.price}  </li>
})

ReactDOM.render(
  <ol>{elements}</ol>,
  document.getElementById('root')
)

III. Building a List Component

It is useful to be able to build a React Component that can dynamically generate a list from an array property that is passed into it.

class ProductList extends React.Component{
  constructor(props){
    super(props)
  }

  render(){
    const elements = this.props.productArray.map( (item,index) => {
      return <li key={item.id}>Product: {item.product} | Price: ${item.price}  </li>
    })
    return <ol>{elements}</ol>
  }
}

const list =[
  {id: 1, product:"Apple", price:3},
  {id: 2, product:"Banana", price:1},
  {id: 3, product:"Carrot", price:2},
  {id: 4, product:"Donuts", price:5},
  {id: 5, product:"Eggplant", price:4}
]

ReactDOM.render(
  <ProductList productArray = {list}/>,
  document.getElementById('root')
)