1

In a Gutenberg block generating a Carousel I set the uniqueId attribute from the clientId of the block and I save it to the markup of the save function as an Html id.

I make that so I can have a unique id, for example, for each Carousel I render to the frontend.

Problem is that I need this unique id also in the frontend js code to pass, for example, different options for each carousel I'm generating. But how can I get this unique id in the js code that will be used in frontend only?

1
  • can you share your code and the markup the block generates? I'm assuming each slide of the carousel is a nested block?
    – Tom J Nowell
    Mar 5 at 20:12
2

One way of getting a unique id for a block in Gutenberg is using the clientId, but in a different way. Given that clientId string is used only once, you can store that in the attributes of the block, which will be stored in the database and you can retrieve it at any given time, the trick is to store the clientId the block gives you, the first time the block mounts, and then stop WordPress from edit that attribute when page reloads. That way, every time you reload the page, you will have a different clientId, but the attribute you saved with the first clientId will still be available in the attributes. The code should look something like this:

import { useEffect } from '@wordpress/element';
import { useBlockProps } from '@wordpress/block-editor';

// ... Whatever else you want to import

export default function Edit({ clientId, attributes, setAttributes }) {
    const blockProps = useBlockProps(); 

    /*useEffect is a React hook that triggers during the component's life 
      cycle parts, but when giving it an empty array as a second argument
      it will only trigger on mounting the component*/

    useEffect(() => {

        //This conditional is useful to only set the id attribute once
        //when the component mounts for the first time

        attributes.id === '' 
        && setAttributes( { "id": clientId } )
    }, [])
    
    //... the rest of your logic goes here


    return (
        <div { ...blockProps }>
            {// You can use attributes.id as a class or id or whatever serves your purpose }
            <div className={attributes.id}>
               //...more JSX or HTML
            </div>                  
        </div>
    );
}

Also, in the attributes prop, you will have to do this:

    "attributes": {
        "id": {
            "type": "string",
            "default": ""
        }

        //...The rest of your attributes
    }

I tested that approach and it works perfectly for a plugin I'm building.

I also read this question that says you can use withInstanceId to get a unique identifier, but I haven't tested that approach yet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.