Skip to content

Commit c9784be

Browse files
committed
useId translation
1 parent 1f49b7d commit c9784be

File tree

1 file changed

+69
-72
lines changed

1 file changed

+69
-72
lines changed
Lines changed: 69 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,26 @@
11
---
2-
title: useId
3-
---
42

5-
<Intro>
3+
## title: useId {/*title-useid*/}
4+
5+
66

7-
`useId` is a React Hook for generating unique IDs that can be passed to accessibility attributes.
7+
`useId` — хук React для генерацыі ўнікальных ідэнтыфікатараў, якія далей можна выкарыстоўваць у атрыбутах даступнасці.
88

99
```js
1010
const id = useId()
1111
```
1212

13-
</Intro>
1413

15-
<InlineToc />
14+
15+
1616

1717
---
1818

19-
## Reference {/*reference*/}
19+
## Апісанне {/*reference*/}
2020

2121
### `useId()` {/*useid*/}
2222

23-
Call `useId` at the top level of your component to generate a unique ID:
23+
Выклічце `useId` на верхнім узроўні вашага кампанента, каб згенераваць унікальны ідэнтыфікатар:
2424

2525
```js
2626
import { useId } from 'react';
@@ -30,39 +30,36 @@ function PasswordField() {
3030
// ...
3131
```
3232
33-
[See more examples below.](#usage)
33+
[Болей прыкладаў глядзіце ніжэй.](#usage)
3434
35-
#### Parameters {/*parameters*/}
35+
#### Параметры {/*parameters*/}
3636
37-
`useId` does not take any parameters.
37+
`useId` не прымае аніякіх параметраў.
3838
39-
#### Returns {/*returns*/}
39+
#### Значэнні, якія вяртаюцца {/*returns*/}
4040
41-
`useId` returns a unique ID string associated with this particular `useId` call in this particular component.
41+
`useId` вяртае радок з унікальным ідэнтыфікатарам, які праасацыяваны з гэтым канкрэтным выклікам `useId` у гэтым канкрэтным кампаненце.
4242
43-
#### Caveats {/*caveats*/}
43+
#### Агаворкі {/*caveats*/}
4444
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).
4649
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+
---
5051
51-
* `useId` currently cannot be used in [async Server Components](/reference/rsc/server-components#async-components-with-server-components).
52+
## Выкарыстанне {/*usage*/}
5253
53-
---
5454
55-
## Usage {/*usage*/}
5655
57-
<Pitfall>
56+
**Не выкарыстоўвайце `useId` для генерацыі ключоў у спісах.** [Ключы мусяць быць згенераванымі на падставе вашых даных](/learn/rendering-lists#where-to-get-your-key).
5857
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)
6058
61-
</Pitfall>
6259
63-
### Generating unique IDs for accessibility attributes {/*generating-unique-ids-for-accessibility-attributes*/}
60+
### Генерацыя ўнікальных ідэнтыфікатараў для атрыбутаў даступнасці {/*generating-unique-ids-for-accessibility-attributes*/}
6461
65-
Call `useId` at the top level of your component to generate a unique ID:
62+
Выклічце `useId` на верхнім узроўні вашага кампанента каб згенераваць унікальны ідэнтыфікатар:
6663
6764
```js [[1, 4, "passwordHintId"]]
6865
import { useId } from 'react';
@@ -72,7 +69,7 @@ function PasswordField() {
7269
// ...
7370
```
7471
75-
You can then pass the <CodeStep step={1}>generated ID</CodeStep> to different attributes:
72+
Далей вы можаце перадаць згенераваны ідэнтыфікатар у розныя атрыбуты:
7673
7774
```js [[1, 2, "passwordHintId"], [1, 3, "passwordHintId"]]
7875
<>
@@ -81,26 +78,26 @@ You can then pass the <CodeStep step={1}>generated ID</CodeStep> to different at
8178
</>
8279
```
8380
84-
**Let's walk through an example to see when this is useful.**
81+
**Давайце разгледзім прыклад, калі гэта можа быць карысна.**
8582
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)` дазваляюць пазначыць, што два тэгі звязаныя адно з адным. Такім чынам, як варыянт, вы можаце адзначыць, што элемент (напрыклад, поле ўводу) апісаны іншым элементам (напрыклад, параграфам).
8784

88-
In regular HTML, you would write it like this:
85+
У звычайным HTML, вы б апісалі гэта так:
8986

9087
```html {5,8}
9188
<label>
92-
Password:
89+
Пароль:
9390
<input
9491
type="password"
9592
aria-describedby="password-hint"
9693
/>
9794
</label>
9895
<p id="password-hint">
99-
The password should contain at least 18 characters
96+
Пароль мусіць змяшчаць як найменш 18 сімвалаў
10097
</p>
10198
```
10299

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`:
104101

105102
```js {4,11,14}
106103
import { useId } from 'react';
@@ -110,23 +107,23 @@ function PasswordField() {
110107
return (
111108
<>
112109
<label>
113-
Password:
110+
Пароль:
114111
<input
115112
type="password"
116113
aria-describedby={passwordHintId}
117114
/>
118115
</label>
119116
<p id={passwordHintId}>
120-
The password should contain at least 18 characters
117+
Пароль мусіць змяшчаць як найменш 18 сімвалаў
121118
</p>
122119
</>
123120
);
124121
}
125122
```
126123

127-
Now, even if `PasswordField` appears multiple times on the screen, the generated IDs won't clash.
124+
Цяпер, нават калі `PasswordField` з’явіцца на старонцы некалькі раз, згенераваныя ідэнтыфікатары не будуць канфліктаваць.
125+
128126

129-
<Sandpack>
130127

131128
```js
132129
import { useId } from 'react';
@@ -136,14 +133,14 @@ function PasswordField() {
136133
return (
137134
<>
138135
<label>
139-
Password:
136+
Пароль:
140137
<input
141138
type="password"
142139
aria-describedby={passwordHintId}
143140
/>
144141
</label>
145142
<p id={passwordHintId}>
146-
The password should contain at least 18 characters
143+
Пароль мусіць змяшчаць як найменш 18 сімвалаў
147144
</p>
148145
</>
149146
);
@@ -152,9 +149,9 @@ function PasswordField() {
152149
export default function App() {
153150
return (
154151
<>
155-
<h2>Choose password</h2>
152+
<h2>Прыдумайце пароль</h2>
156153
<PasswordField />
157-
<h2>Confirm password</h2>
154+
<h2>Пацвердзіце пароль</h2>
158155
<PasswordField />
159156
</>
160157
);
@@ -165,37 +162,37 @@ export default function App() {
165162
input { margin: 5px; }
166163
```
167164

168-
</Sandpack>
169165

170-
[Watch this video](https://www.youtube.com/watch?v=0dNzNcuEuOo) to see the difference in the user experience with assistive technologies.
171166

172-
<Pitfall>
167+
[Азнаёмцеся з відэа](https://www.youtube.com/watch?v=0dNzNcuEuOo), каб пабачыць розніцу ў карыстанні з ужываннем дапаможных тэхналогій.
173168

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.
175169

176-
</Pitfall>
177170

178-
<DeepDive>
171+
Пры [серверным рэндарынгу](/reference/react-dom/server), `**useId` патрабуе ідэнтычнага дрэва кампанентаў на серверы і на кліенце**. Калі дрэвы, што вы рэндарыце і кліенце і серверы не суадносяцца, згенераваныя ідэнтыфікатары будуць адрознымі.
179172

180-
#### Why is useId better than an incrementing counter? {/*why-is-useid-better-than-an-incrementing-counter*/}
181173

182-
You might be wondering why `useId` is better than incrementing a global variable like `nextId++`.
183174

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.
185175

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.
187176

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+
189187

190-
</DeepDive>
191188

192189
---
193190

194-
### Generating IDs for several related elements {/*generating-ids-for-several-related-elements*/}
191+
### Генерацыя ідэнтыфікатараў для некалькі звязаных элементаў {/*generating-ids-for-several-related-elements*/}
192+
193+
Калі вам трэба даць ідэнтыфікатары некалькім звязаным элементам, вы можаце выкарыстаць `useId` каб згенераваць агульны прэфікс для іх:
195194

196-
If you need to give IDs to multiple related elements, you can call `useId` to generate a shared prefix for them:
197195

198-
<Sandpack>
199196

200197
```js
201198
import { useId } from 'react';
@@ -204,10 +201,10 @@ export default function Form() {
204201
const id = useId();
205202
return (
206203
<form>
207-
<label htmlFor={id + '-firstName'}>First Name:</label>
204+
<label htmlFor={id + '-firstName'}>Імя:</label>
208205
<input id={id + '-firstName'} type="text" />
209206
<hr />
210-
<label htmlFor={id + '-lastName'}>Last Name:</label>
207+
<label htmlFor={id + '-lastName'}>Прозвішча:</label>
211208
<input id={id + '-lastName'} type="text" />
212209
</form>
213210
);
@@ -218,22 +215,22 @@ export default function Form() {
218215
input { margin: 5px; }
219216
```
220217

221-
</Sandpack>
222218

223-
This lets you avoid calling `useId` for every single element that needs a unique ID.
219+
220+
Гэта дазволіць вам пазбегнуць выклікаў `useId` для кожнага элемента, які патрабуе ўнікальны ідэнтыфікатар.
224221

225222
---
226223

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` ідэнтыфікатар будзе пачынацца з адрознага прэфікса, які вы ўказалі.
228227

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.
230228

231-
<Sandpack>
232229

233230
```html public/index.html
234231
<!DOCTYPE html>
235232
<html>
236-
<head><title>My app</title></head>
233+
<head><title>Мая праграма</title></head>
237234
<body>
238235
<div id="root1"></div>
239236
<div id="root2"></div>
@@ -246,18 +243,18 @@ import { useId } from 'react';
246243
247244
function PasswordField() {
248245
const passwordHintId = useId();
249-
console.log('Generated identifier:', passwordHintId)
246+
console.log('Згенераваны ідэнтыфікатар:', passwordHintId)
250247
return (
251248
<>
252249
<label>
253-
Password:
250+
Пароль:
254251
<input
255252
type="password"
256253
aria-describedby={passwordHintId}
257254
/>
258255
</label>
259256
<p id={passwordHintId}>
260-
The password should contain at least 18 characters
257+
Пароль мусіць змяшчаць як найменш 18 сімвалаў
261258
</p>
262259
</>
263260
);
@@ -266,7 +263,7 @@ function PasswordField() {
266263
export default function App() {
267264
return (
268265
<>
269-
<h2>Choose password</h2>
266+
<h2>Прыдумайце пароль</h2>
270267
<PasswordField />
271268
</>
272269
);
@@ -305,13 +302,13 @@ root2.render(<App />);
305302
input { margin: 5px; }
306303
```
307304

308-
</Sandpack>
305+
309306

310307
---
311308

312-
### 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*/}
313310

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)
315312

316313
```js
317314
// Server
@@ -335,4 +332,4 @@ const root = hydrateRoot(
335332
);
336333
```
337334

338-
You do not need to pass `identifierPrefix` if you only have one React app on the page.
335+
У `identifierPrefix` няма патрэбы, калі вы маеце толькі адну праграму React на старонцы.

0 commit comments

Comments
 (0)