How to get the post title inside a custom block in a loop? block.js

We can utilize the useSelect hook from the @wordpress/data package to display the post title in custom block within the WordPress block editor. useSelect hook allows us to fetch the post data using the current post ID within the block editor. Here’s the updated code of custom-blocks.js to achieve this.

import { registerBlockType } from '@wordpress/blocks';
import { createElement } from '@wordpress/element';
import { useBlockProps } from '@wordpress/block-editor';
import { useSelect } from '@wordpress/data';

registerBlockType('custom-plugin/custom-name', {
    title: 'Name',
    category: 'common',
    edit: function(props) {
        const blockProps = useBlockProps();

        // Here we are useing useSelect hook to get the current post ID and title.
        const postId = props.clientId.split('-')[0]; // This is to get the post ID from clientId.
        const postTitle = useSelect(select => {
            return select('core/editor').getEditedPostAttribute('title');
        }, [postId]);

        return createElement(
            'p',
            blockProps,
            postTitle || 'No title available'
        );
    },
    save: function() {
        const blockProps = useBlockProps.save();

        return createElement(
            'p',
            blockProps,
            '[[ Gruppe/Titel ]]'
        );
    }
});

tech