Skip to content

Instantly share code, notes, and snippets.

@maheshwaghmare
Created November 14, 2024 13:40
Show Gist options
  • Save maheshwaghmare/3f6762d82c2415da2800619c74d6ecba to your computer and use it in GitHub Desktop.
Save maheshwaghmare/3f6762d82c2415da2800619c74d6ecba to your computer and use it in GitHub Desktop.
Gutenberg | Find blocks by block name - Recursively search for blocks by name within a nested block structure.
// Example usage.
import { parse } from '@wordpress/blocks'

const parsedContent = parse( content, {
	__unstableSkipMigrationLogs: true,
} )

const blocks = findNestedBlocksByName( parsedContent, 'core/paragraph' );
/**
* Recursively search for blocks by name within a nested block structure.
*
* @param {Array} blocks - Array of blocks to search within.
* @param {string} blockName - The block name to search for.
* @returns {Array} - Array of blocks that match the specified name.
*/
function findNestedBlocksByName(blocks, blockName) {
let matchedBlocks = [];
blocks.forEach(block => {
if (block.name === blockName) {
matchedBlocks.push(block);
}
// If the block has innerBlocks, recursively search within them
if (block.innerBlocks && block.innerBlocks.length > 0) {
matchedBlocks = matchedBlocks.concat(findNestedBlocksByName(block.innerBlocks, blockName));
}
});
return matchedBlocks;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment