Skip to content
This repository was archived by the owner on Feb 23, 2024. It is now read-only.

Commit 30c02cb

Browse files
committed
use HOC for component ID
1 parent a21a326 commit 30c02cb

File tree

3 files changed

+39
-22
lines changed

3 files changed

+39
-22
lines changed

assets/js/blocks/product-categories/block.js

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import classnames from 'classnames';
88
/**
99
* Internal dependencies
1010
*/
11-
import uniqueID from '../../utils/uniqueid';
11+
import withComponentID from '../../utils/with-component-id';
1212

1313
/**
1414
* Component displaying the categories as dropdown or list.
@@ -17,7 +17,6 @@ class ProductCategoriesBlock extends Component {
1717
constructor() {
1818
super( ...arguments );
1919
this.select = createRef();
20-
this.id = uniqueID( '', 'wc-block-product-categories' );
2120
this.onNavigate = this.onNavigate.bind( this );
2221
this.renderList = this.renderList.bind( this );
2322
this.renderOptions = this.renderOptions.bind( this );
@@ -71,7 +70,7 @@ class ProductCategoriesBlock extends Component {
7170
}
7271

7372
render() {
74-
const { attributes, categories } = this.props;
73+
const { attributes, categories, componentID } = this.props;
7574
const { className, isDropdown } = attributes;
7675
const classes = classnames(
7776
'wc-block-product-categories',
@@ -82,7 +81,7 @@ class ProductCategoriesBlock extends Component {
8281
}
8382
);
8483

85-
const selectId = `prod-categories-${ this.id }`;
84+
const selectId = `prod-categories-${ componentID }`;
8685

8786
return (
8887
<Fragment>
@@ -123,4 +122,4 @@ class ProductCategoriesBlock extends Component {
123122
}
124123
}
125124

126-
export default ProductCategoriesBlock;
125+
export default withComponentID( ProductCategoriesBlock );

assets/js/utils/uniqueid.js

Lines changed: 0 additions & 17 deletions
This file was deleted.
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import { Component } from 'react';
2+
3+
const ids = [];
4+
5+
/**
6+
* HOC that gives a component a unique ID.
7+
*
8+
* This is an alternative for withInstanceId from @wordpress/compose to avoid using that dependency on the frontend.
9+
*/
10+
const withComponentID = ( OriginalComponent ) => {
11+
return class WrappedComponent extends Component {
12+
generateUniqueID() {
13+
const group = WrappedComponent.name;
14+
15+
if ( ! ids[ group ] ) {
16+
ids[ group ] = 0;
17+
}
18+
19+
ids[ group ]++;
20+
21+
return ids[ group ];
22+
}
23+
24+
render() {
25+
const componentID = this.generateUniqueID();
26+
27+
return <OriginalComponent
28+
{ ...this.props }
29+
componentID={ componentID }
30+
/>;
31+
}
32+
};
33+
};
34+
35+
export default withComponentID;

0 commit comments

Comments
 (0)