Untitled

 avatar
unknown
javascript
a year ago
1.1 kB
8
Indexable
import React from 'react';
import ProductCategoryRow from './ProductCategoryRow';
import ProductRow from './ProductRow';

function ProductTable({ products, filterText, inStockOnly }) {
  const filteredProducts = products.filter(el => (
    el.name.toLowerCase().includes(filterText.toLowerCase()) &&
    (!inStockOnly || (inStockOnly && el.stocked))
  ));

  const rows = filteredProducts.reduce((acc, product) => {
    const isNewCategory = product.category !== acc.lastCategory;

    acc.output.push(isNewCategory ? <ProductCategoryRow key={product.category} category={product.category} /> : null);
    acc.output.push(<ProductRow key={product.name} product={product} />);
    acc.lastCategory = product.category;

    return acc;
  }, { lastCategory: null, output: [] }).output;

  return (
    <table className="product-table">
      <thead>
        <tr>
          <th>Name</th>
          <th>Price</th>
        </tr>
      </thead>
      <tbody>
        {rows}
      </tbody>
    </table>
  );
}

export default ProductTable;
Editor is loading...
Leave a Comment