@wordpress/interactivity-router


目录

The package @wordpress/interactivity-router enables loading content from other pages without a full page reload. Currently, the only supported mode is “region-based”. Full “client-side navigation” is still in experimental phase.

The package defines an Interactivity API store with the core/router namespace, exposing state and 2 actions: navigate and prefetch to handle client-side navigation.

The @wordpress/interactivity-router package was introduced in WordPress Core in v6.5. This means this package is already bundled in Core in any version of WordPress higher than v6.5.

For a comprehensive guide on how client-side navigation works, including getting started, block compatibility, and advanced use cases, see the Client-Side Navigation guide. To learn how to ensure your blocks are compatible with client-side navigation, see the Client-Side Navigation Compatibility guide.

Check the Interactivity API Reference docs in the Block Editor handbook to learn more about the Interactivity API.

Usage

The package is intended to be imported dynamically in the view.js files of interactive blocks. This is done in order to reduce the JS bundle size on the initial page load.

/* view.js */

import { store, withSyncEvent } from '@wordpress/interactivity';

// This is how you would typically use the navigate() action in your block.
store( 'my-namespace/myblock', {
    actions: {
        // The withSyncEvent() utility needs to be used because preventDefault() requires synchronous event access.
        goToPage: withSyncEvent( function* ( e ) {
            e.preventDefault();

            // We import the package dynamically to reduce the initial JS bundle size.
            // Async actions are defined as generators so the import() must be called with `yield`.
            const { actions } =
                yield import( '@wordpress/interactivity-router' );
            yield actions.navigate( e.target.href );
        } ),
    },
} );

Now, you can call actions.navigate() in your block’s view.js file to navigate to a different page or e.g. pass it to a data-wp-on--click attribute.

When loaded, this package adds the following state and actions to the core/router store:

const { state, actions } = store( 'core/router', {
    state: {
        url: window.location.href,
        // `navigating` and `initiator` are also part of the store's state,
        // but they are written by `navigate()` instead of being declared
        // here, so both read `undefined` until the first navigation.
    },
    actions: {
        *navigate(href, options) {...},
        prefetch(url, options) {...},
    }
})

Beyond the current URL, the store’s state describes the navigation itself: whether one is in flight (state.navigating) and who started it (state.initiator). See State below.

The core “Query Loop” block is using this package to provide the region-based navigation.

Directives

data-wp-router-region

It defines a region that is updated on navigation. It requires a unique ID as the value and must be used alongside data-wp-interactive to receive the proper namespace. Router regions can be placed anywhere within interactive regions, including nested interactive elements.

When adding data-wp-router-region to a child element inside a parent with data-wp-interactive, always include data-wp-interactive on the child element as well. This is required for the router region to function correctly.

The value can be a string with the region ID, or a JSON object containing the id and an optional attachTo property.

Example:

<div data-wp-interactive="myblock" data-wp-router-region="main-list">
    <ul>
        <li><a href="/post-1">Post 1</a></li>
        <li><a href="/post-2">Post 2</a></li>
        <li><a href="/post-3">Post 3</a></li>
    </ul>
    <a data-wp-on--click="actions.navigate" href="/page/2">Page 2</a>
</div>

Navigation ignores a router region inside the inert content of a data-wp-html element, whether that’s the server-rendered fallback or HTML the directive inserted, as if the region had no data-wp-router-region attribute. data-wp-html on a router region itself doesn’t make the region’s content inert, because data-wp-router-region takes precedence. See Where to place router regions in the Client-Side Navigation guide.

The attachTo property is a CSS selector that points to the parent element where the new router region should be rendered. This is useful for regions that may not exist on the initial page but are present on subsequent pages, like a modal or an overlay. The router uses the first element on the current page that matches the selector, skipping any element with inert data-wp-html content and anything inside that content.

When navigating between pages:

The router ignores attachTo for a region that the initial page declared with attachTo: on every later page, that region behaves as a regular router region.

Example with attachTo:

<div
    data-wp-interactive="myblock"
    data-wp-router-region='{ "id": "myblock/overlay", "attachTo": "body" }'
>
    I'm in a new region!
</div>

Actions

navigate

Navigates to the specified page.

This function normalizes the passed href, fetches the page HTML if needed, and updates any interactive regions whose contents have changed in the new page. It also creates a new entry in the browser session history.

Params

navigate( href: string, options: NavigateOptions = {} )

prefetch

Prefetches the page for the passed URL. The page is cached and can be used for navigation.

The function normalizes the URL and stores internally the fetch promise, to avoid triggering a second fetch for an ongoing request.

Params

prefetch( url: string, options: PrefetchOptions = {} )

State

All three properties are reactive, so reading them inside a directive or a watch() callback subscribes to their changes.

Neither navigating nor initiator is declared when the store is registered, so both read undefined until the first client-side navigation writes them, and on pages where the router module never loads. Consume them by truthiness — if ( state.navigating ) and state.initiator === myRegionId — rather than comparing against false or null. Note that a binding such as data-wp-bind--aria-busy="state.navigating" renders no attribute at all while the value is undefined, rather than aria-busy="false".

A derived state.initiator carries the region’s id, not the raw data-wp-router-region attribute text. For the JSON object form it is the value of the id property, a namespace:: prefix is stripped, and an empty or non-string id reads null rather than an empty string. Compare against the id you gave the region, spelled exactly as you gave it.

For the full semantics — which navigations are covered and which produce no transition at all, what overlapping navigations do to both readings, and which directive to read them from — see Reacting to the navigation lifecycle in the Client-Side Navigation guide.

Installation

Install the module:

npm install @wordpress/interactivity-router --save

This step is only required if you use the Interactivity API outside WordPress.

Within WordPress, the package is already bundled in Core. To ensure it’s enqueued, add @wordpress/interactivity-router to the dependency array of the script module. This process is often done automatically with tools like wp-scripts.

Furthermore, this package assumes your code will run in an ES2015+ environment. If you’re using an environment with limited or no support for such language features and APIs, you should include the polyfill shipped in @wordpress/babel-preset-default in your code.

License

Interactivity API proposal, as part of Gutenberg and the WordPress project is free software, and is released under the terms of the GNU General Public License version 2 or (at your option) any later version. See LICENSE.md for complete license.


版本号 #2
由 壳壳虫 创建于 2026-10-31 18:21:30 UTC
由 壳壳虫 更新于 2026-10-31 18:21:32 UTC