Now that we can successfully add products, let’s show them in the products listing page, which is managed in the ProductsList component in src/components/ProductsList.js:

import React from 'react'

export default () => {
  return <div>ProductsList</div>
}

Before we do anything else we must pass the products array from App to ProductsList, by adding a render prop like we did in the last lesson for AddProduct:

<Route
  exact
  path="/"
  render={() => <ProductsList products={products} />}
/>

Now in ProductsList, for each product we display the information we have at our disposal:

import React from 'react'

export default props => {
  return (
    <div className="products-list">
      {props.products
        ? props.products.map((value, index) => {
            return (
              <div key={index}>
                <img src={value.image} />
                <h2>{value.name}</h2>
                <p className="description">{value.description}</p>
                <p className="price">${value.price}</p>
              </div>
            )
          })
        : 'No products'}
    </div>
  )
}

We have a way to add products in the AddProduct component. Here we can add a way to remove a product, which we can use in our testing to avoid having lots of sample data and no way to remove a product.

Let’s first add a button, that once clicked calls the deleteProduct() method on the component, and passes it the product index:

<button onClick={e => {
  deleteProduct(index)
  e.stopPropagation()
}}>ⓧ</button>

The onClick event handler has to call stopPropagation() on the event, otherwise the outer onClick handler (that manages the list item click) kicks in.

This is the deleteProduct function called in the event handler:

const deleteProduct = index => {
  props.deleteProduct(index)
}

In App.js, we add deleteProduct as a prop:

<Route
  exact
  path="/"
  render={() => (
    <ProductsList products={products} deleteProduct={deleteProduct} />
  )}
/>

Here’s the deleteProduct method implementation:

const deleteProduct = index => {
  let updatedProducts = [...products]
  updatedProducts = updatedProducts
    .slice(0, index)
    .concat(updatedProducts.slice(index + 1, updatedProducts.length))
  setProducts(updatedProducts)
}

It’s same as we did in the Bills project for bills.

Let’s make the list render a bit nicer with by adding this style to src/App.css:

.products-list {
  display: flex;
  padding-top: 30px;
}
.products-list div {
  width: 33%;

  box-sizing: border-box;
  padding: 30px;
  background-color: lightsalmon;
}

button {
  padding: 30px;
  font-size: 2rem;
}

.description,
.price {
  padding-top: 20px;
}

img {
  max-width: 200px;
}

Here’s our result:


Go to the next lesson