How to get the block unique ID inside edit and save functions on registerBlockType

I'm trying to assign an unique ID into my SVG linearGradient element, this is for a custom Gutenberg block I'm working, basically I need to get access (or generate) an unique id so I can place it into the element HTML id parameter.

I know we have a main block ID we can do styles with CSS and create anchor too, but this is not helpful in what I'm trying to achieve.

I found this https://developer.wordpress.org/block-editor/packages/packages-compose/#withInstanceId but I don't understand how to use it, the docs does't have simple examples to me.

Follow here part of my block code (this does't works):

attributes: {
            id: {
                type: 'string',
                default: withInstanceId(function({instanceId}){ return instanceId })
            }

As you can see, I'm trying to assign the instance ID into an attribute so I can do access it into SAVE and EDIT functions with props.attributes.id

Thanks for any help.


Solution 1:

To get a unique ID inside Gutenberg's Edit and Save Methods You can use clientId Props that provides inside props of Edit and Save Methods.

Example:

First Set Attribute:

attributes: {
   blockId: {
      type: 'string'
   }
}

Inside Edit method

edit: function( props ) {
    const { attributes, setAttributes, clientId } = props;
    const { blockId } = attributes;
    if ( ! blockId ) {
        setAttributes( { blockId: clientId } );
    }
}

Since WP 5.8, you need to wrap the function call with useEffect.

edit: function( props ) {
    const { attributes, setAttributes, clientId } = props;
    const { blockId } = attributes;

    React.useEffect( () => {
        if ( ! blockId ) {
            setAttributes( { blockId: clientId } );
        }
    }, [] );
}

Inside Save method

save: function( props ) {
    const { attributes } = props;
    const { blockId } = attributes;

    // So here `blockId` attribute will have a unique ID

}

Hope it helps!