3

The WordPress block API for Gutenberg has a withInstanceId package.

They say,

Some components need to generate a unique id for each instance. This could serve as suffixes to element ID's for example. Wrapping a component with withInstanceId provides a unique instanceId to serve this purpose.

and show an example:

/**
 * WordPress dependencies
 */
import { withInstanceId } from '@wordpress/compose';

function MyCustomElement( { instanceId } ) {
    return (
        <div id={ `my-custom-element-${ instanceId }` }>
            content
        </div>
    );
}

export default withInstanceId( MyCustomElement );

It seems like it is just being used for html ids? As to not have duplicate id names? Is there any other usage for it? If i just export my component using export default withInstanceId( MyCustomElement ) will the entire component have a unique id?

2 Answers 2

1

The generated id is added to the component's props. So it can be accessed through this.props.instanceId inside the component.

In the example you posted it is being used to assign a unique id attribute to the html element. However it can be used for custom logic inside react. Just as an example, you can assign each component an id and then save its data to the redux store, that way when you need to access the data from an element inside the store you can use its id to find it.

1
  • if you used instanceid for your block and make reusable component using it. it will ask to update reusable component event if you didn't change any content in adding new page. this will happen in WP 5.7.2
    – user8889
    Jun 14, 2021 at 6:05
2

You could use clientId to uniquely identify the block. clientId is available in props.

Something like this..

export function EditBlock({clientId, setAttributes} ) {
  
  // save clientId in attributes to make it available in Save
  return (
        <div id={ `my-custom-element-${ clientId }` }>
            content
        </div>
    ); 
}

No need for HOC.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.