diff --git a/docs/reference-guides/data/data-core-block-editor.md b/docs/reference-guides/data/data-core-block-editor.md index 956e8dd010581..437f7be20f770 100644 --- a/docs/reference-guides/data/data-core-block-editor.md +++ b/docs/reference-guides/data/data-core-block-editor.md @@ -738,6 +738,39 @@ _Returns_ Returns the currently selected block, or null if there is no selected block. +_Usage_ + +```js +import { select } from '@wordpress/data'; +import { store as blockEditorStore } from '@wordpress/block-editor'; + +// Set initial active block client ID +let activeBlockClientId = null; + +const getActiveBlockData = () => { + const activeBlock = select( blockEditorStore ).getSelectedBlock(); + + if ( activeBlock && activeBlock.clientId !== activeBlockClientId ) { + activeBlockClientId = activeBlock.clientId; + + // Get active block name and attributes + const activeBlockName = activeBlock.name; + const activeBlockAttributes = activeBlock.attributes; + + // Log active block name and attributes + console.log( activeBlockName, activeBlockAttributes ); + } +}; + +// Subscribe to changes in the editor +// wp.data.subscribe(() => { +// getActiveBlockData() +// }) + +// Update active block data on click +// onclick="getActiveBlockData()" +``` + _Parameters_ - _state_ `Object`: Global application state. diff --git a/packages/block-editor/src/store/selectors.js b/packages/block-editor/src/store/selectors.js index 210cd26aeaa95..3fdaadb24fc12 100644 --- a/packages/block-editor/src/store/selectors.js +++ b/packages/block-editor/src/store/selectors.js @@ -542,6 +542,39 @@ export function getSelectedBlockClientId( state ) { * * @param {Object} state Global application state. * + * @example + * + *```js + * import { select } from '@wordpress/data' + * import { store as blockEditorStore } from '@wordpress/block-editor' + * + * // Set initial active block client ID + * let activeBlockClientId = null + * + * const getActiveBlockData = () => { + * const activeBlock = select(blockEditorStore).getSelectedBlock() + * + * if (activeBlock && activeBlock.clientId !== activeBlockClientId) { + * activeBlockClientId = activeBlock.clientId + * + * // Get active block name and attributes + * const activeBlockName = activeBlock.name + * const activeBlockAttributes = activeBlock.attributes + * + * // Log active block name and attributes + * console.log(activeBlockName, activeBlockAttributes) + * } + * } + * + * // Subscribe to changes in the editor + * // wp.data.subscribe(() => { + * // getActiveBlockData() + * // }) + * + * // Update active block data on click + * // onclick="getActiveBlockData()" + *``` + * * @return {?Object} Selected block. */ export function getSelectedBlock( state ) {