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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0