Skip to content

Commit 4980928

Browse files
authored
Fix useId updater overwrite (#6788)
1 parent 17ad099 commit 4980928

File tree

2 files changed

+32
-8
lines changed

2 files changed

+32
-8
lines changed

packages/@react-aria/utils/src/useId.ts

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ let canUseDOM = Boolean(
2222
window.document.createElement
2323
);
2424

25-
let idsUpdaterMap: Map<string, (v: string) => void> = new Map();
25+
let idsUpdaterMap: Map<string, Array<(v: string) => void>> = new Map();
2626

2727
/**
2828
* If a default is not provided, generate an id.
@@ -39,7 +39,12 @@ export function useId(defaultId?: string): string {
3939
}, []);
4040

4141
if (canUseDOM) {
42-
idsUpdaterMap.set(res, updateValue);
42+
// TS not smart enough to know that `has` means the value exists
43+
if (idsUpdaterMap.has(res) && !idsUpdaterMap.get(res)!.includes(updateValue)) {
44+
idsUpdaterMap.set(res, [...idsUpdaterMap.get(res)!, updateValue]);
45+
} else {
46+
idsUpdaterMap.set(res, [updateValue]);
47+
}
4348
}
4449

4550
useLayoutEffect(() => {
@@ -71,15 +76,15 @@ export function mergeIds(idA: string, idB: string): string {
7176
return idA;
7277
}
7378

74-
let setIdA = idsUpdaterMap.get(idA);
75-
if (setIdA) {
76-
setIdA(idB);
79+
let setIdsA = idsUpdaterMap.get(idA);
80+
if (setIdsA) {
81+
setIdsA.forEach(fn => fn(idB));
7782
return idB;
7883
}
7984

80-
let setIdB = idsUpdaterMap.get(idB);
81-
if (setIdB) {
82-
setIdB(idA);
85+
let setIdsB = idsUpdaterMap.get(idB);
86+
if (setIdsB) {
87+
setIdsB.forEach(fn => fn(idA));
8388
return idA;
8489
}
8590

packages/react-aria-components/test/TextField.test.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,5 +238,24 @@ describe('TextField', () => {
238238
expect(outerEl[0]).not.toHaveAttribute('id');
239239
expect(input).toHaveAttribute('id', 'name');
240240
});
241+
242+
it('should link an id on the input to the label htmlFor', async () => {
243+
let {getAllByTestId, getByRole, getByText} = render(
244+
<TextField defaultValue="test" data-testid="text-field-test" data-foo="bar">
245+
<Label>Test</Label>
246+
<Input id="name" />
247+
<Text slot="description">Description</Text>
248+
<Text slot="errorMessage">Error</Text>
249+
</TextField>
250+
);
251+
let outerEl = getAllByTestId('text-field-test');
252+
let input = getByRole('textbox');
253+
let label = getByText('Test');
254+
255+
expect(outerEl).toHaveLength(1);
256+
expect(outerEl[0]).not.toHaveAttribute('id');
257+
expect(input).toHaveAttribute('id', 'name');
258+
expect(label).toHaveAttribute('for', 'name');
259+
});
241260
});
242261
});

0 commit comments

Comments
 (0)