Search code examples
phpwordpresswordpress-themingwordpress-gutenberggutenberg-blocks

How to get a unique id with a simple custom gutenberg block in WordPress?


I'm trying get a unique id for each custom gutenberg block. I'm found useInstanceId. Is that possible to use with this syntax?

registerBlockType('custom/block', {
    title: 'Custom',
    
    edit() {
        return (<p>{unqiue-block-id}</p>)
    },
    save() {
        return (<p>{unqiue-block-id}</p>)
    },
});

Solution

  • you could solve this with the clientId out of props. Unfortunately it just lives in the props of the edit function. So you need to deliver the clientId as an extra attribute. I myself was struggling too much getting this with useInstanceId done because you need to make it with a HigherComponent if I understand that right. So I went with the clientId solution.

    I got the initial thought from here

    Here is what your code could look like to get it done with the clientId.

    registerBlockType('custom/block', {
        title: 'Custom',
    
        attributes: {
            yourId: {
                type: 'string',
            }
        },
    
        edit: props => {
            const {
                attributes: {
                    yourId,
                },
                clientId,
                setAttributes,
            } = props;
    
            setAttributes({ yourId: clientId });
    
            return (
                <p>{yourId}</p>
            );
        },
    
        save: props => {
            const {
                attributes: {
                    yourId,
                },
            } = props;
    
            return (
                <p>{yourId}</p>
            );
        },
    });