Skip to content

Commit

Permalink
docs: example for getSelectedBlock (WordPress#66108)
Browse files Browse the repository at this point in the history
* add: example for getSelectedBlock

* change: build docs
  • Loading branch information
troychaplin authored Oct 18, 2024
1 parent 0ae2cb8 commit bcddcb6
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
33 changes: 33 additions & 0 deletions docs/reference-guides/data/data-core-block-editor.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
33 changes: 33 additions & 0 deletions packages/block-editor/src/store/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 ) {
Expand Down

0 comments on commit bcddcb6

Please sign in to comment.