Home › Block and Plugin Tutorials › Block Editor › How to Create a Unique ID for Styling your WordPress Block
How to Create a Unique ID for Styling your WordPress Block

Permanent Unique IDs
This tutorial shows how to generate Unique IDs at runtime. If you need a permanent Unique ID, please check out how to set a permanent unique ID for your block.
Sometimes you need to style your blocks individually, and this is where a unique ID for each block can come in handy. So how do you get one?
Step 1: Add The uniqueId attributeOpens in a new window
Head to your block’s block.json file and add in the uniqueId attribute. Give it a type of string with an empty default.

Step 2: Add the useInstanceId hook to your blockOpens in a new window
Head to your block’s main block file (typically index.js or edit.js) and add in the useInstanceId hook:

useInstanceIdFor the import variation, make sure compose is in your project’s dependencies.
For the alternate variation, include wp-element as part of your block script.

wp_register_script exampleStep 3: Generate the Unique ID on RenderOpens in a new window

In the above example, I pass in a reference to my block and add a prefix of has-cts so the ids are: has-cts-0, has-cts-1
Step 4: Generate the unique ID using useEffectOpens in a new window
Next up is updating the uniqueId attribute. We’ll want to update this each time as WordPress re-calculates unique values on each page refresh.

Step 5: Add the ID to Your Block OutputOpens in a new window

Step 6: Style Your BlockOpens in a new window

Step 7: Style the FrontendOpens in a new window

That’s it!Opens in a new window
Thanks for reading.
Like the tutorial you just read? There's more like it.
There's more where that came from. Enter your email and I'll send you more like it.




