Skip to content

Commit 10f50a0

Browse files
zombieJclaude
andauthored
feat: getId should accept React.Key type (#725)
Change the key parameter type from string to React.Key to support both string and number types, which matches React's key prop type. Co-authored-by: Claude (GLM-4.7) <noreply@anthropic.com>
1 parent fc3221d commit 10f50a0

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

src/hooks/useId.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,13 @@ export function resetUuid() {
2525
* @param key - The key from React element, may contain spaces or invalid characters
2626
* @returns A valid HTML id string
2727
*/
28-
export function getId(prefix: string, key: string): string {
28+
export function getId(prefix: string, key: React.Key): string {
29+
// React.Key can be string | number, convert to string first
30+
const keyStr = String(key);
31+
2932
// Valid id characters: letters, digits, hyphen, underscore, colon, period
3033
// Replace all invalid characters (including spaces) with hyphens to preserve length
31-
const sanitizedKey = key.replace(/[^a-zA-Z0-9_.:-]/g, '-');
34+
const sanitizedKey = keyStr.replace(/[^a-zA-Z0-9_.:-]/g, '-');
3235

3336
return `${prefix}-${sanitizedKey}`;
3437
}

tests/hooks.test.tsx

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -675,6 +675,9 @@ describe('hooks', () => {
675675
expect(getId('btn', 'valid-key_123:456.789')).toBe(
676676
'btn-valid-key_123:456.789',
677677
);
678+
expect(getId('item', 1)).toBe('item-1');
679+
expect(getId('tab', 123)).toBe('tab-123');
680+
expect(getId('panel', 0)).toBe('panel-0');
678681
});
679682
});
680683

0 commit comments

Comments
 (0)