WordPress Plugin and Block Editor Tutorials

Block EditorHow to Create a Unique ID for Styling your WordPress BlockPosted on: December 09, 2022

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:

For 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.

Step 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.

View Tutorial
Shopping Cart
  • Your cart is empty.
Scroll to Top