Load more grid
A product grid whose first page comes with the page and whose "Load more" button fetches the next pages in the browser with useQuery.
Goal: a product grid that shows its first page in the server HTML and adds the next page below it when the shopper presses "Load more", without reloading the page.
| Data | static: products() for the first page; later pages from the browser |
| JavaScript | one island, about 1.9 KB gzip |
| Uses | useQuery('productGridProducts'), products(), page.route |
The block has four files.
The card
The server list and the island draw the same card, so it is its own file. It has no 'use client' and
no @bizzpocket/theme import, so the island bundles only these few lines. Create
blocks/load-more-grid/card.tsx:
import type { Ref } from 'react';
/** The fields of a `Product` the card shows. Plain data, so it can travel to the island as props. */
export interface CardProduct {
id: string;
handle: string;
title: string;
price: { amount: number; currency: string };
image?: { src: string; alt: string } | null;
}
function money(amount: number, currency: string): string {
try {
return new Intl.NumberFormat('en-IN', { style: 'currency', currency }).format(amount);
} catch {
return `${currency} ${amount}`;
}
}
/**
* One product card, used by the server list and by the island. A plain component (no
* 'use client', no @bizzpocket/theme import), so the island bundles only these few lines.
*/
export function Card({ product, linkRef }: { product: CardProduct; linkRef?: Ref<HTMLAnchorElement> | undefined }) {
const src = product.image?.src;
return (
<a ref={linkRef} className="lm-card" href={`/products/${encodeURIComponent(product.handle)}`}>
{src && (src.startsWith('https://') || (src.startsWith('/') && !src.startsWith('//'))) ? (
<img src={src} alt={product.image?.alt ?? ''} width={400} height={400} loading="lazy" decoding="async" />
) : null}
<span className="lm-name">{product.title}</span>
<span className="lm-price">{money(product.price.amount, product.price.currency)}</span>
</a>
);
}The island
Create blocks/load-more-grid/more-products.tsx:
'use client';
import { useEffect, useRef, useState } from 'react';
import { useQuery } from '@bizzpocket/theme/client';
import { Card, type CardProduct } from './card';
type Grid = { products: CardProduct[]; page: number; totalPages: number; total: number };
export interface MoreProductsProps {
collection: string | null;
sort: string | null;
first: number;
/** The page the server rendered, and how many there are. */
page: number;
totalPages: number;
total: number;
/** Products already on the page, so a product never shows twice. */
shownIds: string[];
label: string;
}
export function MoreProducts({ collection, sort, first, page, totalPages, total, shownIds, label }: MoreProductsProps) {
const [last, setLast] = useState(page); // the last page on screen
const [asked, setAsked] = useState<number | null>(null); // the page being fetched
const [extra, setExtra] = useState<CardProduct[]>([]);
const firstNew = useRef<HTMLAnchorElement | null>(null);
const focusIndex = useRef<number | null>(null);
const { data, error, refetch } = useQuery<Grid>(
'productGridProducts',
{ collection: collection ?? undefined, sort: sort ?? undefined, limit: first, page: asked },
{ enabled: asked !== null },
);
// The asked-for page arrived: add its products (skipping any already shown) and stop asking.
useEffect(() => {
if (asked === null || data?.page !== asked) return;
const seen = new Set([...shownIds, ...extra.map((x) => x.id)]);
focusIndex.current = extra.length;
setExtra([...extra, ...data.products.filter((p) => !seen.has(p.id))]);
setLast(asked);
setAsked(null);
}, [asked, data, shownIds, extra]);
// Move focus to the first new card, so a keyboard shopper carries on from there.
useEffect(() => {
if (focusIndex.current !== null && firstNew.current !== null) firstNew.current.focus();
focusIndex.current = null;
}, [extra]);
const loading = asked !== null && error === null;
const shown = shownIds.length + extra.length;
const next = last + 1;
// A real link: before the island wakes up (or without JavaScript) it opens the next page.
const href = `?${sort ? `sort=${encodeURIComponent(sort)}&` : ''}page=${next}`;
return (
<>
{extra.length > 0 ? (
<ul className="lm-grid">
{extra.map((p, i) => (
<li key={p.id}>
<Card product={p} linkRef={i === focusIndex.current ? firstNew : undefined} />
</li>
))}
</ul>
) : null}
<div className="lm-foot">
<p className="lm-status" aria-live="polite">{`Showing ${shown} of ${total}`}</p>
{error !== null ? (
<p role="alert">
{`Could not load more (${error.code}). `}
<button type="button" onClick={refetch}>Try again</button>
</p>
) : null}
{last < totalPages && error === null ? (
<a
className="lm-more"
href={href}
aria-disabled={loading}
onClick={(e) => {
e.preventDefault();
if (asked === null) setAsked(next);
}}
>
{loading ? 'Loading...' : label}
</a>
) : null}
</div>
</>
);
}The block
Create blocks/load-more-grid/load-more-grid.tsx:
import { block, f, products } from '@bizzpocket/theme';
import { Card } from './card';
import { MoreProducts } from './more-products';
import './load-more-grid.css';
export default block({
name: 'Load more grid',
category: 'products',
fields: {
heading: f.text({ default: 'All products' }),
collection: f.collection(),
count: f.number({ default: 8, min: 2, max: 24, integer: true }),
moreLabel: f.text({ default: 'Load more' }),
},
// Static: the first page comes with the page. `?page=` and `?sort=` are passed through,
// so the "Load more" link also works as a plain link to the next page.
data: ({ collection, count }, page) => ({
items: products({ collection, first: count, page: page.route.page, sort: page.route.sort }),
}),
render: ({ heading, collection, count, moreLabel, items }, ctx) => {
const list = items?.products ?? [];
if (list.length === 0) return null;
return (
<section className="lm">
<h2 className="lm-title">{heading}</h2>
<ul className="lm-grid">
{list.map((p) => (
<li key={p.id}>
<Card product={p} />
</li>
))}
</ul>
<MoreProducts
collection={collection ?? null}
sort={ctx.route.sort ?? null}
first={count}
page={items?.page ?? 1}
totalPages={items?.totalPages ?? 1}
total={items?.total ?? list.length}
shownIds={list.map((p) => p.id)}
label={moreLabel}
/>
</section>
);
},
});The CSS
Create blocks/load-more-grid/load-more-grid.css:
.lm { padding: 2rem 1rem; max-width: 80rem; margin: 0 auto; }
.lm-title { margin: 0 0 1rem; }
/* The island's list follows the server's list with the same gap, so the two read as one grid. */
.lm-grid { display: grid; gap: 1rem; grid-template-columns: repeat(2, 1fr); list-style: none; margin: 0 0 1rem; padding: 0; }
@media (min-width: 900px) { .lm-grid { grid-template-columns: repeat(4, 1fr); } }
.lm-card { display: grid; gap: 0.25rem; color: inherit; text-decoration: none; border-radius: 0.5rem; }
.lm-card:focus-visible { outline: 2px solid currentColor; outline-offset: 4px; }
.lm-card img { width: 100%; height: auto; aspect-ratio: 1; object-fit: cover; border-radius: 0.5rem; }
.lm-name { font-weight: 500; }
.lm-foot { display: grid; justify-items: center; gap: 0.75rem; margin-top: 1rem; }
.lm-status { margin: 0; opacity: 0.7; font-size: 0.9rem; }
.lm-more { padding: 0.75rem 2rem; border: 1px solid currentColor; border-radius: 999px; color: inherit; text-decoration: none; font-weight: 600; }
.lm-more[aria-disabled='true'] { opacity: 0.6; pointer-events: none; }Add it with bunx bizzpocket add-to-layout load-more-grid. In bizzpocket dev --mock the sample store
has 30 products, so at the default count of 8 you see "Showing 8 of 30" and the button, and three more
presses load pages 2 to 4 (the last one has 6). The mock honours page, limit, sort and the
priceMin / priceMax / inStock filters, like a real store.
How it works
- Page 1 is server HTML.
products({ collection, first: count, page: page.route.page, sort: page.route.sort })is a static need: the first page is in the page's one data call, visible before any JavaScript, and costs no spinner. - The island only adds.
MoreProductsgets plain data as props: the collection, the sort, the page size, the page the server rendered,totalPages,totaland the ids already shown. It renders the extra products in a second list with the same grid, plus the status line and the button. useQueryfetches a page when asked.enabled: asked !== nullkeeps it idle until the shopper presses the button. Then it callsGET /_bp/q/productGridProducts?v=...with the same variables as the server need (collection,sort,limit,page).undefinedvalues are dropped, so an unset collection means the whole catalogue, as on the server. When the answer for that page arrives, the effect appends its products (skipping any id already shown, in case the catalogue changed) and stops asking.- The button is a link. It points at
?page=2(keepingsort). The island takes over the click, but before it wakes up, or without JavaScript, the link opens page 2 rendered by the server, becausedata()passespage.route.pagethrough. - Keyboard and screen readers. Focus moves to the first new card, and "Showing 16 of 40" is a polite live region.
- Errors. A failed request shows its code (
UPSTREAM,NETWORK...) and "Try again", which callsrefetch()to ask again past the cache. - Caching. Each answer is kept in memory for the visit and shared by every island. On the network, an answer may be cached for 30 seconds, with or without a cookie (details).
JS cost
block server B client gz css gz data
------------------ -------- --------- ------ -------
load-more-grid 2466 1894 423 staticThe island is about 1.9 KB gzip, useQuery included. The default hydrate: 'visible' is right here:
a grid usually starts below the fold, so the island wakes only when the shopper scrolls near it. On the
Bun host, the first island on a page also loads the shared React runtime, once for every island on the
page.
Related
- Data: fetching from the browser: the route, the operations and the cache
- Interactivity:
useQuery() - Collection filters: a grid that pages with links instead
- State