In block.json : { supports: { interactivity: true }, viewScriptModule: file:./view.js }
1/ create directive
data-wp-interactive="namespace"
data-wp-context='{"foo": "bar"}'
→ local state
data-wp-class--{class-name}
the class presence will be tied to a value
data-wp-bind--{attribute-name}
data-wp-on--{event-name}
2/ create a store
- state
- actions
- callback
- getElement()
- getContext()
Example
view.js :
import { store, getContext } from '@wordpress/interactivity';
store( 'wpdsfr', {
actions: {
toggle: () => {
const context = getContext();
context.isOpen = ! context.isOpen;
},
}
} );
render.php
<section
data-wp-interactive="wpdsfr"
data-wp-context='{ "isOpen": false}'
<?php echo get_block_wrapper_attributes(); ?>>
<h3 data-wp-on--click="actions.toggle">
item title
</h3>
<div data-wp-class--is-open="context.isOpen">
<?php echo $content; ?>
</div>
</section>
Sources:
- https://make.wordpress.org/core/2024/03/04/interactivity-api-dev-note/
- https://developer.wordpress.org/news/2024/04/11/a-first-look-at-the-interactivity-api/
- https://developer.wordpress.org/block-editor/reference-guides/interactivity-api/api-reference/#list-of-directives (*)
- https://www.youtube.com/watch?v=49_XlQJYztA&list=LL&index=1