Unique HTML ID in Gutenberg Blocks with useInstanceId

Published
Categories

Recently I was working on building a pair of tabs and tab blocks for a project and needed a way to get a unique ID for each tab that is created. I had previously used withInstanceId but while I was checking the reference for this function I came across useInstanceId also listed.

I didn’t see any examples of how to use it in the handbook but with some searching I came across the pull request where it was added and found plenty of examples in the core blocks, and also lead me to the README.md for the function.

Previously we would pass our edit or save functions to the withInstanceId Higher-Order Component in order to get access to this, but now useInstanceId is available as a React hook we can call directly in our edit function:

import { useInstanceId } from "@wordpress/compose";
import { InnerBlocks, RichText } from "@wordpress/block-editor";

export default function TabEdit({
	attributes,
	setAttributes
}) {
	const instanceId = useInstanceId(TabEdit);
	const { title, id } = attributes;

	setAttributes({ id: instanceId });

	return (
		<div className="tab" id={`tab-block-${id}`}>
			<RichText
				onChange={title => {
					setAttributes({ title });
				}}
				value={title}
				placeholder="Tab title"
			/>
			<InnerBlocks templateLock={false} />
		</div>
	);
}
Code language: JavaScript (javascript)

Really easy way to construct unique HTML IDs for blocks!