You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
`useId` is a React Hook for generating unique IDs that can be passed to accessibility attributes.
7
+
`useId` — хук React для генерацыі ўнікальных ідэнтыфікатараў, якія далей можна выкарыстоўваць у атрыбутах даступнасці.
8
8
9
9
```js
10
10
const id = useId()
11
11
```
12
12
13
-
</Intro>
14
13
15
-
<InlineToc />
14
+
15
+
16
16
17
17
---
18
18
19
-
## Reference {/*reference*/}
19
+
## Апісанне {/*reference*/}
20
20
21
21
### `useId()` {/*useid*/}
22
22
23
-
Call`useId`at the top level of your component to generate a unique ID:
23
+
Выклічце`useId`на верхнім узроўні вашага кампанента, каб згенераваць унікальны ідэнтыфікатар:
24
24
25
25
```js
26
26
import { useId } from'react';
@@ -30,39 +30,36 @@ function PasswordField() {
30
30
// ...
31
31
```
32
32
33
-
[See more examples below.](#usage)
33
+
[Болей прыкладаў глядзіце ніжэй.](#usage)
34
34
35
-
#### Parameters {/*parameters*/}
35
+
#### Параметры {/*parameters*/}
36
36
37
-
`useId`does not take any parameters.
37
+
`useId`не прымае аніякіх параметраў.
38
38
39
-
#### Returns {/*returns*/}
39
+
#### Значэнні, якія вяртаюцца {/*returns*/}
40
40
41
-
`useId`returns a unique ID string associated with this particular `useId`call in this particular component.
41
+
`useId`вяртае радок з унікальным ідэнтыфікатарам, які праасацыяваны з гэтым канкрэтным выклікам `useId`у гэтым канкрэтным кампаненце.
42
42
43
-
#### Caveats {/*caveats*/}
43
+
#### Агаворкі {/*caveats*/}
44
44
45
-
* `useId` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.
45
+
- `useId` — хук, а значыць, вы можаце яго выклікаць толькі **на верхнім узроўні вашага кампанента** ці ўнутры ўласнага хука. Ëн не можа быць выкліканы ўнутры цыкла альбо ўмовы. Калі вы гэтага патрабуеце, выміце ў новы кампанент і перанясіце стан туды.
46
+
- `useId` **не мусіць быць выкарыстаны для генерацыі ключоў кэша** для [use()](/reference/react/use). Ідэнтыфікатар стабільны пакуль кампанент прымантаваны, але можа змяняцца паміж рэндарамі. Ключы кэша мусяць быць згенераванымі на падставе вашых даных.
47
+
- `useId` **не мусіць быць выкарыстаны для генерацыі ключоў** у спісах. [Ключы мусяць быць згенераванымі на падставе вашых даных](/learn/rendering-lists#where-to-get-your-key).
48
+
- `useId` на дадзены момант не можа быць выкарыстаны ўнутры [асінхронных серверных кампанентаў](/reference/rsc/server-components#async-components-with-server-components).
46
49
47
-
* `useId` **should not be used to generate cache keys** for [use()](/reference/react/use). The ID is stable when a component is mounted but may change during rendering. Cache keys should be generated from your data.
48
-
49
-
* `useId` **should not be used to generate keys** in a list. [Keys should be generated from your data.](/learn/rendering-lists#where-to-get-your-key)
50
+
---
50
51
51
-
* `useId` currently cannot be used in [async Server Components](/reference/rsc/server-components#async-components-with-server-components).
52
+
## Выкарыстанне {/*usage*/}
52
53
53
-
---
54
54
55
-
## Usage {/*usage*/}
56
55
57
-
<Pitfall>
56
+
**Не выкарыстоўвайце `useId` для генерацыі ключоў у спісах.** [Ключы мусяць быць згенераванымі на падставе вашых даных](/learn/rendering-lists#where-to-get-your-key).
58
57
59
-
**Do not call `useId` to generate keys in a list.** [Keys should be generated from your data.](/learn/rendering-lists#where-to-get-your-key)
60
58
61
-
</Pitfall>
62
59
63
-
### Generating unique IDs for accessibility attributes {/*generating-unique-ids-for-accessibility-attributes*/}
60
+
### Генерацыя ўнікальных ідэнтыфікатараў для атрыбутаў даступнасці {/*generating-unique-ids-for-accessibility-attributes*/}
64
61
65
-
Call`useId`at the top level of your component to generate a unique ID:
62
+
Выклічце`useId`на верхнім узроўні вашага кампанента каб згенераваць унікальны ідэнтыфікатар:
66
63
67
64
```js [[1, 4, "passwordHintId"]]
68
65
import { useId } from'react';
@@ -72,7 +69,7 @@ function PasswordField() {
72
69
// ...
73
70
```
74
71
75
-
You can then pass the <CodeStep step={1}>generated ID</CodeStep> to different attributes:
72
+
Далей вы можаце перадаць згенераваны ідэнтыфікатар у розныя атрыбуты:
@@ -81,26 +78,26 @@ You can then pass the <CodeStep step={1}>generated ID</CodeStep> to different at
81
78
</>
82
79
```
83
80
84
-
**Let's walk through an example to see when this is useful.**
81
+
**Давайце разгледзім прыклад, калі гэта можа быць карысна.**
85
82
86
-
[HTML accessibility attributes](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA) like [`aria-describedby`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby) let you specify that two tags are related to each other. For example, you can specify that an element (like an input) is described by another element (like a paragraph).
83
+
[Атрыбуты даступнасці ў HTML](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA) як, напрыклад, `[aria-describedby](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby)` дазваляюць пазначыць, што два тэгі звязаныя адно з адным. Такім чынам, як варыянт, вы можаце адзначыць, што элемент (напрыклад, поле ўводу) апісаны іншым элементам (напрыклад, параграфам).
87
84
88
-
In regular HTML, you would write it like this:
85
+
У звычайнымHTML, вы б апісалі гэта так:
89
86
90
87
```html {5,8}
91
88
<label>
92
-
Password:
89
+
Пароль:
93
90
<input
94
91
type="password"
95
92
aria-describedby="password-hint"
96
93
/>
97
94
</label>
98
95
<p id="password-hint">
99
-
The password should contain at least 18characters
96
+
Пароль мусіць змяшчаць як найменш 18 сімвалаў
100
97
</p>
101
98
```
102
99
103
-
However, hardcoding IDs like this is not a good practice in React. A component may be rendered more than once on the page--but IDs have to be unique! Instead of hardcoding an ID, generate a unique ID with`useId`:
100
+
Але ўказваць ідэнтыфікатар наўпрост у кодзе не з’яўляецца добрай практыкай у React. Кампанент можа быць адрэндараны болей за адзін раз на старонцы, а ідэнтыфікатары маюць быць унікальнымі! Замест указання пастаяннага ідэнтыфікатара, згенеруйце ўнікальны з дапамогай`useId`:
104
101
105
102
```js {4,11,14}
106
103
import { useId } from 'react';
@@ -110,23 +107,23 @@ function PasswordField() {
110
107
return (
111
108
<>
112
109
<label>
113
-
Password:
110
+
Пароль:
114
111
<input
115
112
type="password"
116
113
aria-describedby={passwordHintId}
117
114
/>
118
115
</label>
119
116
<p id={passwordHintId}>
120
-
The password should contain at least 18characters
117
+
Пароль мусіць змяшчаць як найменш 18 сімвалаў
121
118
</p>
122
119
</>
123
120
);
124
121
}
125
122
```
126
123
127
-
Now, even if `PasswordField` appears multiple times on the screen, the generated IDs won't clash.
124
+
Цяпер, нават калі `PasswordField` з’явіцца на старонцы некалькі раз, згенераваныя ідэнтыфікатары не будуць канфліктаваць.
125
+
128
126
129
-
<Sandpack>
130
127
131
128
```js
132
129
import { useId } from 'react';
@@ -136,14 +133,14 @@ function PasswordField() {
136
133
return (
137
134
<>
138
135
<label>
139
-
Password:
136
+
Пароль:
140
137
<input
141
138
type="password"
142
139
aria-describedby={passwordHintId}
143
140
/>
144
141
</label>
145
142
<p id={passwordHintId}>
146
-
The password should contain at least 18characters
143
+
Пароль мусіць змяшчаць як найменш 18 сімвалаў
147
144
</p>
148
145
</>
149
146
);
@@ -152,9 +149,9 @@ function PasswordField() {
152
149
export default function App() {
153
150
return (
154
151
<>
155
-
<h2>Choose password</h2>
152
+
<h2>Прыдумайце пароль</h2>
156
153
<PasswordField />
157
-
<h2>Confirm password</h2>
154
+
<h2>Пацвердзіце пароль</h2>
158
155
<PasswordField />
159
156
</>
160
157
);
@@ -165,37 +162,37 @@ export default function App() {
165
162
input { margin: 5px; }
166
163
```
167
164
168
-
</Sandpack>
169
165
170
-
[Watch this video](https://www.youtube.com/watch?v=0dNzNcuEuOo) to see the difference in the user experience with assistive technologies.
171
166
172
-
<Pitfall>
167
+
[Азнаёмцеся з відэа](https://www.youtube.com/watch?v=0dNzNcuEuOo), каб пабачыць розніцу ў карыстанні з ужываннем дапаможных тэхналогій.
173
168
174
-
With [server rendering](/reference/react-dom/server), **`useId` requires an identical component tree on the server and the client**. If the trees you render on the server and the client don't match exactly, the generated IDs won't match.
175
169
176
-
</Pitfall>
177
170
178
-
<DeepDive>
171
+
Пры [серверным рэндарынгу](/reference/react-dom/server), `**useId` патрабуе ідэнтычнага дрэва кампанентаў на серверы і на кліенце**. Калі дрэвы, што вы рэндарыце і кліенце і серверы не суадносяцца, згенераваныя ідэнтыфікатары будуць адрознымі.
179
172
180
-
#### Why is useId better than an incrementing counter? {/*why-is-useid-better-than-an-incrementing-counter*/}
181
173
182
-
You might be wondering why `useId` is better than incrementing a global variable like `nextId++`.
183
174
184
-
The primary benefit of `useId` is that React ensures that it works with [server rendering.](/reference/react-dom/server) During server rendering, your components generate HTML output. Later, on the client, [hydration](/reference/react-dom/client/hydrateRoot) attaches your event handlers to the generated HTML. For hydration to work, the client output must match the server HTML.
185
175
186
-
This is very difficult to guarantee with an incrementing counter because the order in which the Client Components are hydrated may not match the order in which the server HTML was emitted. By calling `useId`, you ensure that hydration will work, and the output will match between the server and the client.
187
176
188
-
Inside React, `useId` is generated from the "parent path" of the calling component. This is why, if the client and the server tree are the same, the "parent path" will match up regardless of rendering order.
177
+
#### Чым useId лепей за нарастальнага лічыльнік? {/*why-is-useid-better-than-an-incrementing-counter*/}
178
+
179
+
Вы можаце задумацца: чым `useId` лепей за нарастальную глабальную пераменную накшталт `nextId++`.
180
+
181
+
Асноўная перавага `useId` у тым, што React забяспечваю працу пры [серверным рэндарынгу](/reference/react-dom/server). Падчас сервернага рэндарынгу, з вашых кампанентаў генеруецца HTML. Потым, на кліенце, падчас [гідратацыі](/reference/react-dom/client/hydrateRoot) адбываецца прывязка апрацоўшчыкаў падзей да згенераванага HTML. Каб гідратацыя спрацавала, вынік кліента мусіць супадаць з HTML сервера.
182
+
183
+
Гэта вельмі складана гарантаваць праз нарастальны лічыльнік, бо парадак, у якім кліент робіць гідратацыю кампанентаў, можа не адпавядаць парадку, у якім сервер складае HTML. Карыстаючыся `useId`, можна гарантаваць, што гідрадацыя спрацуе, і вынік будзе аднолькавым на серверы і кліенце.
184
+
185
+
Унутры React, `useId` генеруецца на падставе размяшчэння бацькоўскага кампанента». Менавіта таму, калі дрэвы кліента і сервера ідэнтычныя, «размяшчэнне бацькоўскага кампанента» будзе адпавядаць незалежна ад парадку рэндара.
186
+
189
187
190
-
</DeepDive>
191
188
192
189
---
193
190
194
-
### Generating IDs for several related elements {/*generating-ids-for-several-related-elements*/}
191
+
### Генерацыя ідэнтыфікатараў для некалькі звязаных элементаў {/*generating-ids-for-several-related-elements*/}
192
+
193
+
Калі вам трэба даць ідэнтыфікатары некалькім звязаным элементам, вы можаце выкарыстаць `useId` каб згенераваць агульны прэфікс для іх:
195
194
196
-
If you need to give IDs to multiple related elements, you can call `useId` to generate a shared prefix for them:
197
195
198
-
<Sandpack>
199
196
200
197
```js
201
198
import { useId } from 'react';
@@ -204,10 +201,10 @@ export default function Form() {
@@ -218,22 +215,22 @@ export default function Form() {
218
215
input { margin: 5px; }
219
216
```
220
217
221
-
</Sandpack>
222
218
223
-
This lets you avoid calling `useId` for every single element that needs a unique ID.
219
+
220
+
Гэта дазволіць вам пазбегнуць выклікаў `useId` для кожнага элемента, які патрабуе ўнікальны ідэнтыфікатар.
224
221
225
222
---
226
223
227
-
### Specifying a shared prefix for all generated IDs {/*specifying-a-shared-prefix-for-all-generated-ids*/}
224
+
### Вызначэнне агульнага прэфікса для ўсіх згенераваных ідэнтыфікатараў {/*specifying-a-shared-prefix-for-all-generated-ids*/}
225
+
226
+
Калі вы рэндарыце некалькі незалежных праграм React на адной старонцы, перадайце `identifierPrefix` у опцыях да вашых выклікаў `[createRoot](/reference/react-dom/client/createRoot#parameters)` ці `[hydrateRoot](/reference/react-dom/client/hydrateRoot)`. Гэта гарантуе, што ідэнтыфікатары з дзвюх розных праграм не будуць канфліктаваць, бо кожны згенераваны праз `useId` ідэнтыфікатар будзе пачынацца з адрознага прэфікса, які вы ўказалі.
228
227
229
-
If you render multiple independent React applications on a single page, pass `identifierPrefix` as an option to your [`createRoot`](/reference/react-dom/client/createRoot#parameters) or [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) calls. This ensures that the IDs generated by the two different apps never clash because every identifier generated with `useId` will start with the distinct prefix you've specified.
230
228
231
-
<Sandpack>
232
229
233
230
```html public/index.html
234
231
<!DOCTYPE html>
235
232
<html>
236
-
<head><title>My app</title></head>
233
+
<head><title>Мая праграма</title></head>
237
234
<body>
238
235
<div id="root1"></div>
239
236
<div id="root2"></div>
@@ -246,18 +243,18 @@ import { useId } from 'react';
### Using the same ID prefix on the client and the server {/*using-the-same-id-prefix-on-the-client-and-the-server*/}
309
+
### Выкарыстанне аднолькавых прэфіксаў для ідэнтыфікатараў на кліенце і на серверы {/*using-the-same-id-prefix-on-the-client-and-the-server*/}
313
310
314
-
If you [render multiple independent React apps on the same page](#specifying-a-shared-prefix-for-all-generated-ids), and some of these apps are server-rendered, make sure that the `identifierPrefix` you pass to the [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) call on the client side is the same as the `identifierPrefix` you pass to the [server APIs](/reference/react-dom/server) such as [`renderToPipeableStream`.](/reference/react-dom/server/renderToPipeableStream)
311
+
Калі вы [рэндарыце некалькі незалежных праграм React на адной старонцы](#specifying-a-shared-prefix-for-all-generated-ids), і некаторыя з гэтых праграм рэндарацца на серверы, пераканайцеся, што `identifierPrefix`, які вы перадаяце ў выклік `[hydrateRoot](/reference/react-dom/client/hydrateRoot)` на кліенце, ідэнтычны `identifierPrefix`, які вы перадаяце праз [API сервера](/reference/react-dom/server), такія як `[renderToPipeableStream`.](/reference/react-dom/server/renderToPipeableStream)
315
312
316
313
```js
317
314
// Server
@@ -335,4 +332,4 @@ const root = hydrateRoot(
335
332
);
336
333
```
337
334
338
-
You do not need to pass `identifierPrefix`if you only have one React app on the page.
335
+
У `identifierPrefix`няма патрэбы, калі вы маеце толькі адну праграму React на старонцы.
0 commit comments