How to Access Parent Block ID and Index of Current InnerBlock in Gutenberg Custom Block?

438 views Asked by At

I'm working with Advanced Custom Fields (ACF) to create custom blocks for the WordPress Gutenberg editor. I have designed a parent block named "Tabs" that can contain multiple inner blocks, each named "Tab".

Here's a simple representation of what I'm trying to achieve:

// Parent Block: Tabs (render.php file)
<Tabs>
  <InnerBlocks />
</Tabs>

// InnerBlock: Tab (render.php file)
// Inside this block, I need to access the ID of the parent (Tabs) 
// and also the current index or position of this inner block (Tab).

My challenge is to access:

  1. The ID of the parent block (Tabs) from inside each Tab inner block.
  2. The current index or position of the Tab inner block within the inner block itself.

Given that I'm using ACF for block creation, how might I retrieve this information in the render.php file of my custom blocks?

Has anyone worked on something similar or can guide me through this?

1

There are 1 answers

2
ValentinG On

Index

Maybe is not the better solution, but there is an approach In your Tab.tsx you can add this :

  const index = select('core/block-editor').getBlockIndex(props.clientId);

  useEffect(() => {
    setAttributes({ index });
  }, [index, setAttributes]);

Of course you need to add index attributes when you register your component

Parent Id

For the parent id, below an approach to get the context of your parent

  const parentClientId = select(
    'core/block-editor',
  ).getBlockHierarchyRootClientId(props.clientId);
  const parentAttributes = select('core/block-editor').getBlock(parentClientId);

Parent Id #2

You have another approach that you can explore, it's to add context to Tabs.tsx

registerBlockType('stackoverflow/tabs', {
  title: 'tabs',
  description: 'tabs',
  category: 'widgets',
  attributes: {
    id: { type: 'string' },
  },
  providesContext: {
    id: 'id',
  },
  edit: YourEditFile,
  save: YourSaveFile,
});

And in Tab.tsx recover the context

registerBlockType('stackoverflow/tab', {
  usesContext: ['id'],
});

To read it in your Tab.tsx you can do this

const { id } = props.context;

Php Only

Provide Context

Provide your block id to child with the attribute

// Parent block
register_block_type('plugin-name-parent', array(
  'editor_script' => 'script-name',
  'editor_style' => 'style-name',
  'render_callback' => 'render_callback_parent',
  'provides_context' => ['name_context', 'name_attribute'],
);

// Child block
register_block_type('plugin-name', array(
  'editor_script' => 'script-name',
  'editor_style' => 'style-name',
  'render_callback' => 'render_callback',
  'uses_context' => ['name_context'],
);

function render_callback($attributes, $content, $block)
{
  $context = $block->context['name_context']; // Can be your parent id
}