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 attribute
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 block
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 Render

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 useEffect
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 Output

Step 6: Style Your Block

Step 7: Style the Frontend

That’s it!
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.




