BizzPocket

Blocks: block()

On this page

A block is one section of a page, such as a header, a hero or a product grid. It is one folder in blocks/ with one file whose default export is block({ ... }). This page lists every option of block(), the rules render follows, and what the page adds around your HTML.

tsx
import { block, f } from '@bizzpocket/theme';

export default block({
  name: 'Hello',
  category: 'content',
  fields: { text: f.text({ default: 'Hello from your new theme' }) },
  render: ({ text }) => <h1>{text}</h1>,
});

The folder name is the block's type: blocks/hello/hello.tsx is the block hello. Layouts refer to it by that name (layouts.md). There is nothing to register.

Contents: Options · render · What the page adds · Errors · CSS · Examples · Legacy ids


All the options

Only name and render are required.

Option Type Default What it does
name string required The name the seller sees in the page editor.
render (props, ctx) => ReactNode required Turns the props and the data into HTML. Synchronous. See render.
category one of the categories below made from the type (else 'content') The group the editor lists the block under.
description string none One line under the name in the editor.
fields { key: f.* } {} What the seller can edit. Each key becomes a prop of render, typed. See fields.md.
data (props, page) => ({ name: helper(...) }) none Describes the data the block needs. The page fetches it. See data.md.
load async (ctx) => object none The escape hatch: async data, run on every request, never cached. Not with data. See data.md.
hydrate 'load' | 'idle' | 'visible' 'visible' When the block's islands become interactive. No effect on a block without islands. See interactivity.md.
lcp boolean false This block holds the page's biggest visible element (the Largest Contentful Paint), usually the hero picture.
aboveFold boolean false This block is visible without scrolling.
role one of the roles below made from the type (else none) The job the block does on a page, such as the product page's main block.
type, variant string the folder name Legacy ids for migrated themes. Do not set them. See Legacy ids.

name, description, category

What the seller sees when they add a block. category is one of:

header, footer, hero, products, collections, content, media, social-proof, promo, commerce, account, utility.

Without category, the build picks one from the role or the type name, and falls back to content. Set it: it is one word and it puts the block where sellers look for it. A container's f.blocks({ allow }) can also accept "every block of a category" ('category:media', see group.md).

fields

A map of field builders. The seller's saved values arrive in render (and in data()) as props, cleaned and with defaults filled in: a f.number({ min: 1, max: 12 }) is always a number from 1 to 12. A block may have at most one f.blocks() field, at the top level of fields; block() throws otherwise. All field kinds: fields.md.

data and load

data(props, page) returns an object of needs (products(...), product(...), menu(...)...). It does not fetch. The page fetches every block's needs in one call and passes each result to render under the name you gave it. Every result can be null. Keep data() a plain mapping and the block is static (fetched with the page); any branching makes it runtime (one more fetch). The rules: data.md.

load(ctx) is async and runs on the server for every request. Public operations go without the shopper's cookie and keep the page cacheable; customer* operations run as the shopper and make the page private, no-store (limits.md). Its result is merged into render's props. Use it only when data() cannot express what you need.

Setting both throws Block "<name>" sets both data and load; they are mutually exclusive.

hydrate

Applies to all islands ('use client' files) of the block:

  • 'visible' (default): when the island comes near the screen;
  • 'idle': when the browser is idle;
  • 'load': as soon as the page's scripts load. Use it for a header menu or a cart button.

lcp and aboveFold

Both make the block critical. The page waits for its data before it sends the first part of the HTML, and that data comes in the first line of the page call. Other blocks stream in after. The first picture of the first block in that first part is loaded eagerly with high priority; give the main <Image> of an lcp block priority too.

Mark one lcp block per page and only what is really on screen as aboveFold. Each critical block delays the first byte until its data is ready. More: data.md.

role

A role says the block does a job a page needs. The roles are:

header, footer, product-detail, cart, checkout, login, signup, account, order-list, order-detail, wishlist, policy, search-results, not-found, order-return, order-cancel, blog-list, blog-post, content.

What a role changes:

  • The build warns when a layout lacks a role its page expects: layouts/product.json has no block with role "product-detail"; the editor expects one. Each page type expects the role of the same name (product expects product-detail, orders expects order-list, search expects search-results...).
  • The editor places header and footer blocks only in the global layout, and any other role only on the page that expects it. A block with no role can go on any page.

Without role, the build derives one from a few known type names: header, footer, cart, login-form, signup-form, account-dashboard, order-list, order-detail, order-return, order-cancel, wishlist-grid, policy-content, search-results, not-found, and any type that is or starts with product-detail. Anything else has no role. Set role yourself on any block that does one of these jobs under another name.


render

tsx
render: (props, ctx) => ReactNode

props holds the field values (with defaults), the results of data() under your names (or what load() returned), and, for a container, its rendered children under the f.blocks() key.

ctx is the second argument:

ctx. What it is
store { slug, name, currency } of the store being shown
route the page: pageType, handle, q, page, sort, filters (as page.route in data())
blockId this block's id from the layout. Unique on the page: use it to make HTML ids.

The rules:

  • render is synchronous. It returns JSX, a string or null. It is never async and never fetches. Data comes from data() or load().
  • Return null to show nothing. For example when a list is empty. Do not show a heading over nothing.
  • Cope with null data. A need is null when its argument is missing, the store has nothing, or the fetch failed.
  • Hooks and event handlers do not run in a block file. The block is rendered on the server once. Put state and onClick in a 'use client' file (interactivity.md). Using a hook in a server file stops the build with CLIENT_HOOK_IN_SERVER.
  • block() freezes the definition. Its options cannot be swapped after the build has read them.

What the page adds around a block

You render the block's content. The page wraps it in a <section>:

html
<section data-block-type="announcement-bar" data-block-id="6f1d1f0e-9c1a-4a43-8d6a-1d2b6a0a1003">
  <p class="ab">Free shipping on orders over ₹999<a class="ab-link" href="/shop">Shop now</a></p>
</section>
Attribute When
data-block-type always: the block's type
data-block-id always: the block's id in the layout
style when the block has trait fields (f.spacing(), f.colorScheme(), f.typography()): their CSS variables (fields.md)
data-bp-container on a container (a block with f.blocks())
data-bp-hide when the layout node limits visibility.devices: the devices it is hidden on (layouts.md). On a 2.x block in the Next.js storefront it sits on a display: contents wrapper instead
data-bp-critical on an lcp / aboveFold block (Bun renderer)
data-bp-error on a block that threw (the section is then empty)

So do not add your own outer <section> with the same job, and do not rely on being the first child of <body> or <main>. A block whose data is still streaming is a <div data-bp-placeholder> with the same data-block-type and data-block-id until it fills in.


When a block throws

Each block renders on its own. If render throws, that block becomes an empty section and the error is logged on the server (without its stack). The rest of the page renders normally, and no error text reaches the HTML. A container that throws renders empty, without its children; a child that throws does not affect its siblings.

If load() throws or is too slow, the block renders with {} from load(), so check for missing keys.


CSS

Import the block's CSS in the block file:

tsx
import './announcement-bar.css';
  • It loads only on pages that use the block.
  • It is plain CSS (minified at build time). All blocks share one page, so prefix your classes with something unique to the block (ab-, fc-...).
  • CSS imported by components the block uses is included too, in import order.
  • Theme-wide CSS goes in styles/global.css (theme-config.md).

The css gz column of the size report shows each block's CSS size.


Examples

A block with fields only

No data, no JavaScript. Create blocks/announcement-bar/announcement-bar.tsx:

blocks/announcement-bar/announcement-bar.tsx
import { block, f, Link } from '@bizzpocket/theme';
import './announcement-bar.css';

export default block({
  name: 'Announcement bar',
  category: 'promo',
  description: 'One line of text across the top of the page, with an optional link.',
  fields: {
    message: f.text({ default: 'Free shipping on orders over ₹999' }),
    linkLabel: f.text({ default: 'Shop now' }),
    linkHref: f.link({ default: '/shop' }),
  },
  render: ({ message, linkLabel, linkHref }) => (
    <p className="ab">
      {message}
      {linkHref ? <Link href={linkHref} className="ab-link">{linkLabel}</Link> : null}
    </p>
  ),
});

And blocks/announcement-bar/announcement-bar.css:

blocks/announcement-bar/announcement-bar.css
.ab { margin: 0; padding: 0.5rem 1rem; text-align: center; background: var(--colors-primary); color: var(--colors-background); }
.ab-link { margin-left: 0.5rem; color: inherit; text-decoration: underline; }

--colors-primary comes from the theme's tokens (theme-config.md).

A hero: lcp

Create blocks/hero-banner/hero-banner.tsx:

blocks/hero-banner/hero-banner.tsx
import { block, f, Image, Link } from '@bizzpocket/theme';

export default block({
  name: 'Hero banner',
  category: 'hero',
  description: 'A large picture with a headline and a button.',
  // The page's biggest picture: its HTML is in the first bytes the shopper gets.
  lcp: true,
  fields: {
    headline: f.text({ default: 'New season, new toys' }),
    picture: f.image({ label: 'Picture' }),
    buttonLabel: f.text({ default: 'Shop now' }),
    buttonHref: f.link({ default: '/shop' }),
  },
  render: ({ headline, picture, buttonLabel, buttonHref }) => (
    <div className="hero">
      {picture ? <Image src={picture.src} alt={picture.alt ?? ''} width={1600} height={900} sizes="100vw" priority /> : null}
      <h1>{headline}</h1>
      {buttonHref ? <Link href={buttonHref}>{buttonLabel}</Link> : null}
    </div>
  ),
});

f.image() is { src, alt? } or undefined until the seller picks a picture, so check it first.

Data and ctx

A product page block that reads the product in the URL. Create blocks/product-summary/product-summary.tsx:

blocks/product-summary/product-summary.tsx
import { block, product, Money } from '@bizzpocket/theme';

export default block({
  name: 'Product summary',
  category: 'commerce',
  description: 'The title and price of the product in the URL.',
  data: (_props, page) => ({
    item: product({ handle: page.route.handle }),
  }),
  // `ctx` is the second argument: the store, the route and this block's id.
  render: ({ item }, ctx) => {
    if (!item) return null;
    const titleId = `${ctx.blockId}-title`;
    return (
      <div aria-labelledby={titleId}>
        <h1 id={titleId}>{item.title}</h1>
        <Money amount={item.price.amount} currency={item.price.currency} />
        <p>Sold by {ctx.store.name}</p>
      </div>
    );
  },
});

The size report shows static: the product is fetched in the page call. On a product page the API already loads the routed product, so this need costs nothing extra. It has no role: it sits next to the page's product-detail block instead of replacing it.

An interactive part: hydrate

Create blocks/size-guide/size-guide-button.tsx, an island:

blocks/size-guide/size-guide-button.tsx
'use client';
import { useState } from 'react';

export function SizeGuideButton({ label, html }: { label: string; html: string }) {
  const [open, setOpen] = useState(false);
  return (
    <div>
      <button type="button" aria-expanded={open} onClick={() => setOpen(!open)}>
        {label}
      </button>
      {open ? <div dangerouslySetInnerHTML={{ __html: html }} /> : null}
    </div>
  );
}

And the block, blocks/size-guide/size-guide.tsx:

blocks/size-guide/size-guide.tsx
import { block, f } from '@bizzpocket/theme';
import { SizeGuideButton } from './size-guide-button';

export default block({
  name: 'Size guide',
  category: 'utility',
  // Wake the island as soon as the page's scripts load, not when it scrolls into view.
  hydrate: 'load',
  fields: {
    label: f.text({ default: 'Size guide' }),
    guide: f.richText({ default: '<p>S: 2 to 3 years. M: 4 to 5 years. L: 6 to 7 years.</p>' }),
  },
  render: ({ label, guide }) => <SizeGuideButton label={label} html={guide} />,
});

f.richText() is cleaned with an allowlist before it reaches render, so passing it to dangerouslySetInnerHTML is safe. Island props must be JSON (no functions, no JSX).

The size report for these four blocks:

block             server B  client gz  css gz  data
----------------  --------  ---------  ------  ------
announcement-bar       693          0     145  none
hero-banner            927          0       0  none
product-summary        799          0       0  static
size-guide             442        268       0  none

Only size-guide sends JavaScript. data is none for blocks without data() or load().

More examples

  • A block that holds other blocks (f.blocks()): group.md
  • load(): data.md
  • Cart buttons, carousels and accordions without your own JavaScript: interactivity.md

Legacy ids: type and variant

A block's type is its folder name. type and variant exist only for themes moved from 2.x: bizzpocket migrate sets them so the layouts sellers already saved keep pointing at the right block.

tsx
block({
  type: 'product-grid', // the 2.x type saved layouts use
  variant: 'grid-best-sellers-toyshop', // one of several looks of that type
  name: 'Best sellers grid',
  // ...
});

Several folders may then share one type with different variants. A layout node picks one with variantId; without it, the theme's defaultVariants (in theme.config.ts) or the variant named like the type is used. A new theme does not need any of this: leave both out.

Next: layouts.md.