Skip to content

Commit

Permalink
Ignore prefix in useId() when it is falsey (#21848)
Browse files Browse the repository at this point in the history
* Ignore prefix in useId() when it is falsey.

This commit updates the useId() hook to ignore the `prefix`
param in the returned id when `prefix` is falsey.

Previously `prefix` was always concatenated into the returned
id string but its default value is `undefined` so this would
result in IDs like "undefined123". After this change useId()
returns IDs like "123" when `prefix` is falsey.

* Change files

* Update packages/react-utilities/src/hooks/useId.ts

Co-authored-by: ling1726 <[email protected]>

* Provide default value to useId() prefix

Sets the default value of useId()'s first argument, prefix, to "fui-".

Co-authored-by: ling1726 <[email protected]>
  • Loading branch information
spmonahan and ling1726 authored Feb 28, 2022
1 parent 978542b commit 1940164
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"type": "prerelease",
"comment": "Ignore prefix in useId() when it is falsey.",
"packageName": "@fluentui/react-utilities",
"email": "[email protected]",
"dependentChangeType": "patch"
}
6 changes: 6 additions & 0 deletions packages/react-utilities/src/hooks/useId.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ describe('useId', () => {
expect(result.current).toMatch(/^foo/);
});

it('defaults to "fui-" when prefix is not specified', () => {
const { result } = renderHook(() => useId());

expect(result.current).toMatch(/^fui-/);
});

it('uses the same ID without prefix', () => {
const { result, rerender } = renderHook(() => useId());
const firstResult = result.current;
Expand Down
12 changes: 9 additions & 3 deletions packages/react-utilities/src/hooks/useId.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,19 @@ export function resetIdsForTests(): void {
/**
* Hook to generate a unique ID.
*
* @param prefix - Optional prefix for the ID
* @param prefix - Optional prefix for the ID. Defaults to 'fui-'.
* @param providedId - Optional id provided by a parent component. Defaults to the provided value if present,
* without conditioning the hook call
* @returns The ID
*/
export function useId(prefix?: string, providedId?: string): string {
export function useId(prefix: string = 'fui-', providedId?: string): string {
const contextValue = useSSRContext();

return React.useMemo(() => providedId || `${prefix}${++contextValue.current}`, [prefix, providedId, contextValue]);
return React.useMemo(() => {
if (providedId) {
return providedId;
}

return `${prefix}${++contextValue.current}`;
}, [prefix, providedId, contextValue]);
}

0 comments on commit 1940164

Please sign in to comment.