components#ProductsGrid JavaScript Examples
The following examples show how to use
components#ProductsGrid.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: all-products.js From gatsby-shopify-course with BSD Zero Clause License | 4 votes |
export default function AllProducts() {
const { products, collections } = React.useContext(ProductContext);
const collectionProductMap = {};
const { search } = useLocation();
const qs = queryString.parse(search);
const selectedCollectionIds = qs.c?.split(',').filter(c => !!c) || [];
const selectedCollectionIdsMap = {};
const searchTerm = qs.s;
selectedCollectionIds.forEach(collectionId => {
selectedCollectionIdsMap[collectionId] = true;
});
if (collections) {
collections.forEach(collection => {
collectionProductMap[collection.shopifyId] = {};
collection.products.forEach(product => {
collectionProductMap[collection.shopifyId][product.shopifyId] = true;
});
});
}
const filterByCategory = product => {
if (Object.keys(selectedCollectionIdsMap).length) {
for (let key in selectedCollectionIdsMap) {
if (collectionProductMap[key]?.[product.shopifyId]) {
return true;
}
}
return false;
}
return true;
};
const filterBySearchTerm = product => {
if (searchTerm) {
return product.title.toLowerCase().indexOf(searchTerm.toLowerCase()) >= 0;
}
return true;
};
const filteredProducts = products
.filter(filterByCategory)
.filter(filterBySearchTerm);
return (
<Layout>
<SEO
description="The MadHatter store all products"
title="All products"
/>
{!!searchTerm && !!filteredProducts.length && (
<h3>
Search term: <strong>'{searchTerm}'</strong>
</h3>
)}
{!!filteredProducts.length && <h4>{filteredProducts.length} products</h4>}
<Content>
<Filters />
{!filteredProducts.length && (
<div>
<h3>
<span>Oh no! Nothing matches</span>
<strong>'{searchTerm}'</strong>
</h3>
<div>
To help with your search why not try:
<br />
<br />
<ul>
<li>Checking your spelling</li>
<li>Using less words</li>
<li>Try using a different search term</li>
</ul>
</div>
</div>
)}
{!!filteredProducts.length && (
<div>
<ProductsGrid products={filteredProducts} />
</div>
)}
</Content>
</Layout>
);
}