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
Copy file name to clipboardExpand all lines: src/content/reference/react/useId.md
+53-57Lines changed: 53 additions & 57 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,7 +4,7 @@ title: useId
4
4
5
5
<Intro>
6
6
7
-
`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
constid=useId()
@@ -16,11 +16,11 @@ const id = useId()
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,35 @@ 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.
46
-
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
-
51
-
* `useId` currently cannot be used in [async Server Components](/reference/rsc/server-components#async-components-with-server-components).
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).
52
49
53
50
---
54
51
55
-
## Usage {/*usage*/}
52
+
## Выкарыстанне {/*usage*/}
56
53
57
54
<Pitfall>
58
55
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)
56
+
**Не выкарыстоўвайце `useId`для генерацыі ключоў у спісах.** [Ключы мусяць генерыравацца на падставе вашых даных](/learn/rendering-lists#where-to-get-your-key).
60
57
61
58
</Pitfall>
59
+
### Генерацыя ўнікальных ідэнтыфікатараў для атрыбутаў даступнасці {/*generating-unique-ids-for-accessibility-attributes*/}
62
60
63
-
### Generating unique IDs for accessibility attributes {/*generating-unique-ids-for-accessibility-attributes*/}
64
-
65
-
Call `useId` at the top level of your component to generate a unique ID:
61
+
Выклічце `useId` на верхнім узроўні вашага кампанента каб згенераваць унікальны ідэнтыфікатар:
66
62
67
63
```js [[1, 4, "passwordHintId"]]
68
64
import { useId } from'react';
@@ -72,7 +68,7 @@ function PasswordField() {
72
68
// ...
73
69
```
74
70
75
-
You can then pass the <CodeStep step={1}>generated ID</CodeStep> to different attributes:
71
+
Далей вы можаце перадаць згенераваны ідэнтыфікатар у розныя атрыбуты:
@@ -81,26 +77,26 @@ You can then pass the <CodeStep step={1}>generated ID</CodeStep> to different at
81
77
</>
82
78
```
83
79
84
-
**Let's walk through an example to see when this is useful.**
80
+
**Давайце разгледзім прыклад, калі гэта можа быць карысна.**
85
81
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).
82
+
[Атрыбуты даступнасці ў 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
83
88
-
In regular HTML, you would write it like this:
84
+
У звычайным HTML, вы б апісалі гэта так:
89
85
90
86
```html {5,8}
91
87
<label>
92
-
Password:
88
+
Пароль:
93
89
<input
94
90
type="password"
95
91
aria-describedby="password-hint"
96
92
/>
97
93
</label>
98
94
<p id="password-hint">
99
-
The password should contain at least 18characters
95
+
Пароль мусіць змяшчаць як мінімум 18сімвалаў
100
96
</p>
101
97
```
102
98
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`:
99
+
Але ўказанне ідэнтыфікатара наўпрост у кодзе не з’яўляецца добрай практыкай у React. На старонцы кампанент можа быць адрэндараны болей за адзін раз, а ідэнтыфікатары павінны быць унікальнымі! Замест указання пастаяннага ідэнтыфікатара, згенеруйце ўнікальны з дапамогай`useId`:
104
100
105
101
```js {4,11,14}
106
102
import { useId } from'react';
@@ -110,21 +106,21 @@ function PasswordField() {
110
106
return (
111
107
<>
112
108
<label>
113
-
Password:
109
+
Пароль:
114
110
<input
115
111
type="password"
116
112
aria-describedby={passwordHintId}
117
113
/>
118
114
</label>
119
115
<p id={passwordHintId}>
120
-
The password should contain at least 18characters
116
+
Пароль мусіць змяшчаць як мінімум 18сімвалаў
121
117
</p>
122
118
</>
123
119
);
124
120
}
125
121
```
126
122
127
-
Now, even if`PasswordField`appears multiple times on the screen, the generated IDs won't clash.
123
+
Цяпер, нават калі`PasswordField`з’явіцца на старонцы некалькі разоў, згенераваныя ідэнтыфікатары не будуць канфліктаваць.
128
124
129
125
<Sandpack>
130
126
@@ -136,14 +132,14 @@ function PasswordField() {
136
132
return (
137
133
<>
138
134
<label>
139
-
Password:
135
+
Пароль:
140
136
<input
141
137
type="password"
142
138
aria-describedby={passwordHintId}
143
139
/>
144
140
</label>
145
141
<p id={passwordHintId}>
146
-
The password should contain at least 18characters
142
+
Пароль мусіць змяшчаць як мінімум 18сімвалаў
147
143
</p>
148
144
</>
149
145
);
@@ -152,9 +148,9 @@ function PasswordField() {
152
148
exportdefaultfunctionApp() {
153
149
return (
154
150
<>
155
-
<h2>Choose password</h2>
151
+
<h2>Прыдумайце пароль</h2>
156
152
<PasswordField />
157
-
<h2>Confirm password</h2>
153
+
<h2>Пацвердзіце пароль</h2>
158
154
<PasswordField />
159
155
</>
160
156
);
@@ -167,33 +163,33 @@ input { margin: 5px; }
167
163
168
164
</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.
166
+
[Азнаёмцеся з відэа](https://www.youtube.com/watch?v=0dNzNcuEuOo), каб убачыць розніцу ў карыстальніцкім досведзе пры выкарыстанні дапаможных тэхналогій.
171
167
172
168
<Pitfall>
173
169
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.
170
+
Пры [серверным рэндарынгу](/reference/react-dom/server), **`useId`патрабуе ідэнтычнага дрэва кампанентаў на серверы і на кліенце**. Калі дрэвы, што вы рэндарыце на кліенце і серверы не супадаюць, згенераваныя ідэнтыфікатары будуць адрознымі.
175
171
176
172
</Pitfall>
177
173
178
174
<DeepDive>
179
175
180
-
#### Why is useId better than an incrementing counter? {/*why-is-useid-better-than-an-incrementing-counter*/}
176
+
#### Чаму useId лепей за інкрэментальны лічыльнік? {/*why-is-useid-better-than-an-incrementing-counter*/}
181
177
182
-
You might be wondering why `useId`is better than incrementing a global variable like`nextId++`.
178
+
Вы можаце задумацца: чаму `useId`лепей за інкрэментальную глабальную пераменную накшталт`nextId++`.
183
179
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.
180
+
Асноўная перавага `useId`у тым, што React забяспечвае працу пры [серверным рэндарынгу](/reference/react-dom/server). Падчас сервернага рэндарынгу, з вашых кампанентаў генеруецца HTML. Потым, на кліенце, падчас [гідратацыі](/reference/react-dom/client/hydrateRoot) адбываецца прывязка апрацоўшчыкаў падзей да згенераванага HTML. Каб гідратацыя спрацавала, вынік кліента мусіць супадаць з HTML сервера.
185
181
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.
182
+
Гэта вельмі цяжка гарантаваць праз інкрэментальны лічыльнік, бо парадак, у якім кліент робіць гідратацыю кампанентаў, можа не адпавядаць парадку, у якім сервер складае HTML. Карыстаючыся `useId`, можна гарантаваць, што гідрадацыя спрацуе, і вынік будзе аднолькавым і на серверы, і кліенце.
187
183
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.
184
+
Унутры React, `useId`генеруецца на падставе размяшчэння бацькоўскага кампанента». Менавіта таму, калі дрэвы кліента і сервера ідэнтычныя, «размяшчэнне бацькоўскага кампанента» будзе супадаць незалежна ад парадку рэндара.
189
185
190
186
</DeepDive>
191
187
192
188
---
193
189
194
-
### Generating IDs for several related elements {/*generating-ids-for-several-related-elements*/}
190
+
### Генерацыя ідэнтыфікатараў для некалькі звязаных элементаў {/*generating-ids-for-several-related-elements*/}
195
191
196
-
If you need to give IDs to multiple related elements, you can call`useId`to generate a shared prefix for them:
192
+
Калі вам трэба даць ідэнтыфікатары некалькім звязаным элементам, вы можаце выкарыстаць`useId`каб згенераваць агульны прэфікс для іх:
197
193
198
194
<Sandpack>
199
195
@@ -204,10 +200,10 @@ export default function Form() {
This lets you avoid calling`useId`for every single element that needs a unique ID.
219
+
Гэта дазволіць вам пазбегнуць выклікаў`useId`для кожнага элемента, які патрабуе ўнікальны ідэнтыфікатар.
224
220
225
221
---
226
222
227
-
### Specifying a shared prefix for all generated IDs {/*specifying-a-shared-prefix-for-all-generated-ids*/}
223
+
### Вызначэнне агульнага прэфікса для ўсіх згенераваных ідэнтыфікатараў {/*specifying-a-shared-prefix-for-all-generated-ids*/}
228
224
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.
225
+
Калі вы рэндарыце некалькі незалежных праграм React на адной старонцы, перадайце`identifierPrefix`у опцыях да вашых выклікаў [`createRoot`](/reference/react-dom/client/createRoot#parameters) ці [`hydrateRoot`](/reference/react-dom/client/hydrateRoot). Гэта гарантуе, што ідэнтыфікатары з дзвюх розных праграм не будуць канфліктаваць, бо кожны згенераваны праз `useId`ідэнтыфікатар будзе пачынацца з адрознага прэфікса, які вы ўказалі.
230
226
231
227
<Sandpack>
232
228
233
229
```html public/index.html
234
230
<!DOCTYPE html>
235
231
<html>
236
-
<head><title>My app</title></head>
232
+
<head><title>Мая праграма</title></head>
237
233
<body>
238
234
<div id="root1"></div>
239
235
<div id="root2"></div>
@@ -246,18 +242,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*/}
308
+
### Выкарыстанне аднолькавых прэфіксаў для ідэнтыфікатараў на кліенце і на серверы {/*using-the-same-id-prefix-on-the-client-and-the-server*/}
313
309
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)
310
+
Калі вы [рэндарыце некалькі незалежных праграм 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
311
316
312
```js
317
313
// Server
@@ -335,4 +331,4 @@ const root = hydrateRoot(
335
331
);
336
332
```
337
333
338
-
You do not need to pass `identifierPrefix`if you only have one React app on the page.
334
+
У `identifierPrefix`няма патрэбы, калі вы маеце толькі адну праграму React на старонцы.
0 commit comments