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.