Artı Teknoloji - Teknolojiye Artı
Modern Gutenberg Block Development: React, @wordpress/scripts & Interactivity API - Baskı Önizleme

+- Artı Teknoloji - Teknolojiye Artı (https://www.artiteknoloji.com)
+-- Forum: Web Tabanlı Uygulamalar (https://www.artiteknoloji.com/forumdisplay.php?fid=44)
+--- Forum: WordPress (https://www.artiteknoloji.com/forumdisplay.php?fid=47)
+--- Konu Başlığı: Modern Gutenberg Block Development: React, @wordpress/scripts & Interactivity API (/showthread.php?tid=578)



Modern Gutenberg Block Development: React, @wordpress/scripts & Interactivity API - Wertomy® - 19-11-2026

Modern Gutenberg Block Development: React, @wordpress/scripts & Interactivity API

For over a decade, WordPress developers extended page layouts by registering fragile [shortcode] tags backed by messy regex parsers, metabox soup, and heavyweight jQuery scripts loaded globally across every frontend URL. Today, the Gutenberg Block Editor and Full Site Editing (FSE) have transformed WordPress into a structured, component-driven visual architecture. By building custom blocks with declarative block.json metadata, zero-config @wordpress/scripts Webpack/Babel pipelines, dynamic server-side PHP render.php templates, and the native WordPress Interactivity API, engineers ship ultra-fast, reactive user interfaces—such as live pricing calculators, filterable product grids, and interactive FAQ accordions—with less than 15 KB of runtime JavaScript and zero jQuery bloat.



Evolution of WordPress UI Components: Shortcodes vs. Static vs. Interactivity API

Choosing the right block rendering architecture determines whether your site suffers from validation errors after plugin updates or enjoys rock-solid Core Web Vitals and seamless editor previews:

[table]
[tr]
[td]Architecture Pattern[/td]
[td]Editor Experience[/td]
[td]Frontend Rendering & Hydration[/td]
[td]Best Engineering Use Case[/td]
[/tr]
[tr]
[td]Legacy [shortcode][/td]
[td]Opaque raw text string; zero visual WYSIWYG feedback[/td]
[td]Server-rendered PHP + manual global jQuery enqueue[/td]
[td]Deprecated — retain only for backward compatibility[/td]
[/tr]
[tr]
[td]Static React Block (save.js)[/td]
[td]Live React component inside Gutenberg canvas[/td]
[td]Serialized HTML saved directly in post_content[/td]
[td]Hero banners, callout boxes, static comparison grids[/td]
[/tr]
[tr]
[td]Dynamic Block (render.php)[/td]
[td]Live <ServerSideRender> or React preview[/td]
[td]Rendered dynamically on server per request via PHP[/td]
[td]Latest posts, live stock tickers, user-personalized widgets[/td]
[/tr]
[tr]
[td]Dynamic + Interactivity API[/td]
[td]Full React editor controls + live state preview[/td]
[td]SSR HTML hydrated via declarative data-wp-* directives[/td]
[td]Tabs, modals, live search filters, shopping cart drawers[/td]
[/tr]
[/table]

Zero-Config Build Pipelines with @wordpress/scripts and block.json

Modern WordPress block engineering eliminates manual Webpack, Babel, PostCSS, and ESLint configuration boilerplate through the official @wordpress/scripts package. Scaffolding a multi-block plugin with npx @wordpress/create-block@latest generates a clean src/ -> build/ structure anchored by block.json (Metadata API v3):

Kod:
{
  "$schema": "https://schemas.wp.org/trunk/block.json",
  "apiVersion": 3,
  "name": "acme/interactive-pricing-toggle",
  "version": "1.2.0",
  "title": "Interactive SaaS Pricing Toggle",
  "category": "widgets",
  "icon": "calculator",
  "description": "Monthly vs. Annual billing switcher powered by the WordPress Interactivity API.",
  "supports": {
    "html": false,
    "align": ["wide", "full"],
    "interactivity": true,
    "color": {
      "background": true,
      "text": true
    },
    "spacing": {
      "padding": true,
      "margin": true
    }
  },
  "attributes": {
    "monthlyPrice": {
      "type": "number",
      "default": 49
    },
    "annualDiscountPercent": {
      "type": "number",
      "default": 20
    },
    "planName": {
      "type": "string",
      "default": "Enterprise Cloud"
    }
  },
  "editorScript": "file:./index.js",
  "editorStyle": "file:./index.css",
  "style": "file:./style-index.css",
  "render": "file:./render.php",
  "viewScriptModule": "file:./view.js"
}
Notice three critical block.json properties that optimize performance automatically:
  • Conditional Asset Loading (viewScriptModule): WordPress core inspects post_content before rendering the page header and enqueues view.js (as a modern ES Module) and style-index.css strictly on pages that actually contain acme/interactive-pricing-toggle—delivering zero unused JavaScript on standard blog articles.
  • Native Theme.json Design Token Inheritance: Declaring "supports": { "color": ..., "spacing": ... } binds your custom block directly into the site’s Global Styles palette, typography presets, and responsive fluid spacing tokens without writing custom color pickers.
  • Server-Side render.php Elimination of Block Validation Errors: When markup lives inside render.php instead of a serialized save.js string, updating HTML structure or accessibility attributes in future plugin releases never triggers the dreaded *"This block contains unexpected or invalid content"* warning in Gutenberg!

Alıntı:Prefer dynamic render.php blocks paired with the Interactivity API over static save.js blocks for complex interactive components: you eliminate block validation breakage across updates while delivering SEO-ready server-rendered HTML on first byte.

Building Reactive Frontend UI with the WordPress Interactivity API

Previously, adding client-side interactivity to a Gutenberg block forced developers either to bundle a heavy 45 KB React runtime onto the public frontend or fall back to imperative DOM manipulation. Introduced natively into WordPress core, the **Interactivity API** uses lightweight Preact signals (~10 KB gzipped) driven by declarative HTML attributes (data-wp-interactive, data-wp-context, data-wp-on--click, and data-wp-text):

Kod:
<?php
// src/render.php — Server-Rendered HTML Hydrated Seamlessly on Client
$monthly = (float) ($attributes['monthlyPrice'] ?? 49);
$discount = (float) ($attributes['annualDiscountPercent'] ?? 20);
$annualMonthly = round($monthly * (1 - $discount / 100), 2);

$context = wp_json_encode([
    'isAnnual'      => true,
    'monthlyPrice'  => $monthly,
    'annualPrice'   => $annualMonthly,
]);

$wrapper_attributes = get_block_wrapper_attributes([
    'class'               => 'acme-pricing-card',
    'data-wp-interactive' => 'acme/pricing',
    'data-wp-context'     => $context,
]);
?>

<div <?php echo $wrapper_attributes; ?>>
    <h3><?php echo esc_html($attributes['planName']); ?></h3>

    <div class="pricing-toggle-bar">
        <button
            type="button"
            data-wp-on--click="actions.toggleBilling"
            data-wp-bind--aria-pressed="context.isAnnual"
        >
            Switch Monthly / Annual (Save <?php echo esc_html($discount); ?>%)
        </button>
    </div>

    <p class="pricing-amount">
        $<span data-wp-text="state.displayedPrice"><?php echo esc_html($annualMonthly); ?></span>
        <span>/ month</span>
    </p>
</div>
And here is the matching ES Module controller (src/view.js) registering reactive derived getters and click actions:

Kod:
// src/view.js — Declarative Interactivity API Store
import { store, getContext } from '@wordpress/interactivity';

store('acme/pricing', {
    state: {
        get displayedPrice() {
            const ctx = getContext();
            return ctx.isAnnual ? ctx.annualPrice : ctx.monthlyPrice;
        },
    },
    actions: {
        toggleBilling() {
            const ctx = getContext();
            ctx.isAnnual = !ctx.isAnnual;
        },
    },
});
Look at how cleanly server-side PHP and client-side reactivity align: the initial HTML arrives from the server already displaying the default annual price ($39.20) with zero Cumulative Layout Shift (CLS), and clicking the toggle button updates the DOM instantaneously via fine-grained signal reactivity. Even better, multiple pricing blocks on the exact same page maintain completely isolated local state through getContext() without ID collisions!

Editor Ergonomics: InspectorControls, Block Variations, and Custom Hooks

Great Gutenberg engineering treats content editors as first-class users:
  1. Keep the Canvas Focused and Controls in InspectorControls: Allow editors to type headings and descriptions inline on the block canvas using <RichText>, while placing numeric pricing inputs, toggle switches, and layout selectors inside the right-hand <InspectorControls> sidebar using <PanelBody>, <NumberControl>, and <ToggleControl>.
  2. Register Block Variations & Patterns Instead of Duplicate Blocks: Rather than building five separate testimonial or feature-card blocks, build one versatile block and register curated **Block Variations** (registerBlockVariation) and **Block Patterns** (register_block_pattern) so editors insert pre-styled layouts in one click.

By combining block.json asset scoping, @wordpress/scripts modern bundling, render.php server templates, and the declarative **Interactivity API**, WordPress developers build expressive, resilient block libraries that rival dedicated front-end frameworks while preserving native FSE compatibility.