Skip to content

Commit e41ff41

Browse files
authored
chore: Internal unique ID utilities (#135)
1 parent 0d2e191 commit e41ff41

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed

src/internal/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,4 @@ export { default as handleKey } from './utils/handle-key';
3838
export { default as circleIndex } from './utils/circle-index';
3939
export { default as Portal, PortalProps } from './portal';
4040
export { useMergeRefs } from './use-merge-refs';
41+
export { useRandomId, useUniqueId } from './use-unique-id';
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
import React from 'react';
5+
import { render } from '@testing-library/react';
6+
7+
import { useUniqueId, useRandomId } from '../index';
8+
9+
function DemoRandomIdComponent() {
10+
const id = useRandomId();
11+
return <div>{id}</div>;
12+
}
13+
14+
function DemoUniqueIdComponent({ prefix }: { prefix: string }) {
15+
const id = useUniqueId(prefix);
16+
return <div>{id}</div>;
17+
}
18+
19+
it('generates random ID per component', () => {
20+
const component1 = render(<DemoRandomIdComponent />);
21+
const textContent1 = component1.container.textContent;
22+
23+
const component2 = render(<DemoRandomIdComponent />);
24+
const textContent2 = component2.container.textContent;
25+
26+
expect(textContent1).not.toBe('');
27+
expect(textContent1).not.toBe(textContent2);
28+
29+
component1.rerender(<DemoRandomIdComponent />);
30+
expect(component1.container.textContent).toBe(textContent1);
31+
});
32+
33+
it('creates unique ID with given prefix', () => {
34+
const component = render(<DemoUniqueIdComponent prefix="prefix-" />);
35+
36+
expect(component.container.textContent).toContain('prefix-');
37+
});
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
import React, { useRef } from 'react';
5+
6+
let counter = 0;
7+
export const useRandomId = () => {
8+
const idRef = useRef<string | null>(null);
9+
if (!idRef.current) {
10+
idRef.current = `${counter++}-${Date.now()}-${Math.round(Math.random() * 10000)}`;
11+
}
12+
return idRef.current;
13+
};
14+
15+
const useId: typeof useRandomId = (React as any).useId ?? useRandomId;
16+
17+
export function useUniqueId(prefix?: string) {
18+
return `${prefix ? prefix : ''}` + useId();
19+
}

0 commit comments

Comments
 (0)