Related to this issue

I’m trying to get the index of a child block within a parent, to use in the php rendering as a tab index.

Attempting to add this code to the Child itself, so on save it can assign the current child’s index within the parent as an attribute for use in the PHP template.
const index = select( 'core/block-editor' ).getBlockIndex( clientId );

This is constantly returning -1, even though the clientId is unique across blocks. Any suggestions/help?

1 Answer
1

Without the root id the block is looked for at the top-level1. Something like this seems to work:

useSelect(select => {
    const editor = select('core/block-editor')
    const rootId = editor.getBlockRootClientId(blockId)
    return editor.getBlockIndex(blockId, rootId)
}, [blockId])

[1] https://github.com/WordPress/gutenberg/blob/v9.9.3/packages/block-editor/src/store/selectors.js#L945

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *