File tree Expand file tree Collapse file tree 3 files changed +57
-0
lines changed
Expand file tree Collapse file tree 3 files changed +57
-0
lines changed Original file line number Diff line number Diff line change @@ -38,3 +38,4 @@ export { default as handleKey } from './utils/handle-key';
3838export { default as circleIndex } from './utils/circle-index' ;
3939export { default as Portal , PortalProps } from './portal' ;
4040export { useMergeRefs } from './use-merge-refs' ;
41+ export { useRandomId , useUniqueId } from './use-unique-id' ;
Original file line number Diff line number Diff line change 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+ } ) ;
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments