Skip to content

Commit ae4836d

Browse files
authored
Merge pull request #159 from reactjs/useId
useId translation
2 parents a47ef7d + c4d0366 commit ae4836d

File tree

1 file changed

+53
-57
lines changed

1 file changed

+53
-57
lines changed

src/content/reference/react/useId.md

Lines changed: 53 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ title: useId
44

55
<Intro>
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()
@@ -16,11 +16,11 @@ const id = useId()
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,35 @@ 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.
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).
5249
5350
---
5451
55-
## Usage {/*usage*/}
52+
## Выкарыстанне {/*usage*/}
5653
5754
<Pitfall>
5855
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).
6057
6158
</Pitfall>
59+
### Генерацыя ўнікальных ідэнтыфікатараў для атрыбутаў даступнасці {/*generating-unique-ids-for-accessibility-attributes*/}
6260
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` на верхнім узроўні вашага кампанента каб згенераваць унікальны ідэнтыфікатар:
6662
6763
```js [[1, 4, "passwordHintId"]]
6864
import { useId } from 'react';
@@ -72,7 +68,7 @@ function PasswordField() {
7268
// ...
7369
```
7470
75-
You can then pass the <CodeStep step={1}>generated ID</CodeStep> to different attributes:
71+
Далей вы можаце перадаць згенераваны ідэнтыфікатар у розныя атрыбуты:
7672
7773
```js [[1, 2, "passwordHintId"], [1, 3, "passwordHintId"]]
7874
<>
@@ -81,26 +77,26 @@ You can then pass the <CodeStep step={1}>generated ID</CodeStep> to different at
8177
</>
8278
```
8379
84-
**Let's walk through an example to see when this is useful.**
80+
**Давайце разгледзім прыклад, калі гэта можа быць карысна.**
8581
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) дазваляюць пазначыць, што два тэгі звязаныя адзін з адным. Такім чынам, як варыянт, вы можаце адзначыць, што элемент (напрыклад, поле ўводу) апісаны іншым элементам (напрыклад, параграфам).
8783
88-
In regular HTML, you would write it like this:
84+
У звычайным HTML, вы б апісалі гэта так:
8985
9086
```html {5,8}
9187
<label>
92-
Password:
88+
Пароль:
9389
<input
9490
type="password"
9591
aria-describedby="password-hint"
9692
/>
9793
</label>
9894
<p id="password-hint">
99-
The password should contain at least 18 characters
95+
Пароль мусіць змяшчаць як мінімум 18 сімвалаў
10096
</p>
10197
```
10298
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`:
104100
105101
```js {4,11,14}
106102
import { useId } from 'react';
@@ -110,21 +106,21 @@ function PasswordField() {
110106
return (
111107
<>
112108
<label>
113-
Password:
109+
Пароль:
114110
<input
115111
type="password"
116112
aria-describedby={passwordHintId}
117113
/>
118114
</label>
119115
<p id={passwordHintId}>
120-
The password should contain at least 18 characters
116+
Пароль мусіць змяшчаць як мінімум 18 сімвалаў
121117
</p>
122118
</>
123119
);
124120
}
125121
```
126122
127-
Now, even if `PasswordField` appears multiple times on the screen, the generated IDs won't clash.
123+
Цяпер, нават калі `PasswordField` з’явіцца на старонцы некалькі разоў, згенераваныя ідэнтыфікатары не будуць канфліктаваць.
128124
129125
<Sandpack>
130126
@@ -136,14 +132,14 @@ function PasswordField() {
136132
return (
137133
<>
138134
<label>
139-
Password:
135+
Пароль:
140136
<input
141137
type="password"
142138
aria-describedby={passwordHintId}
143139
/>
144140
</label>
145141
<p id={passwordHintId}>
146-
The password should contain at least 18 characters
142+
Пароль мусіць змяшчаць як мінімум 18 сімвалаў
147143
</p>
148144
</>
149145
);
@@ -152,9 +148,9 @@ function PasswordField() {
152148
export default function App() {
153149
return (
154150
<>
155-
<h2>Choose password</h2>
151+
<h2>Прыдумайце пароль</h2>
156152
<PasswordField />
157-
<h2>Confirm password</h2>
153+
<h2>Пацвердзіце пароль</h2>
158154
<PasswordField />
159155
</>
160156
);
@@ -167,33 +163,33 @@ input { margin: 5px; }
167163
168164
</Sandpack>
169165
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), каб убачыць розніцу ў карыстальніцкім досведзе пры выкарыстанні дапаможных тэхналогій.
171167
172168
<Pitfall>
173169
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` патрабуе ідэнтычнага дрэва кампанентаў на серверы і на кліенце**. Калі дрэвы, што вы рэндарыце на кліенце і серверы не супадаюць, згенераваныя ідэнтыфікатары будуць адрознымі.
175171
176172
</Pitfall>
177173
178174
<DeepDive>
179175
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*/}
181177
182-
You might be wondering why `useId` is better than incrementing a global variable like `nextId++`.
178+
Вы можаце задумацца: чаму `useId` лепей за інкрэментальную глабальную пераменную накшталт `nextId++`.
183179
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 сервера.
185181
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`, можна гарантаваць, што гідрадацыя спрацуе, і вынік будзе аднолькавым і на серверы, і кліенце.
187183
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` генеруецца на падставе размяшчэння бацькоўскага кампанента». Менавіта таму, калі дрэвы кліента і сервера ідэнтычныя, «размяшчэнне бацькоўскага кампанента» будзе супадаць незалежна ад парадку рэндара.
189185
190186
</DeepDive>
191187
192188
---
193189
194-
### Generating IDs for several related elements {/*generating-ids-for-several-related-elements*/}
190+
### Генерацыя ідэнтыфікатараў для некалькі звязаных элементаў {/*generating-ids-for-several-related-elements*/}
195191
196-
If you need to give IDs to multiple related elements, you can call `useId` to generate a shared prefix for them:
192+
Калі вам трэба даць ідэнтыфікатары некалькім звязаным элементам, вы можаце выкарыстаць `useId` каб згенераваць агульны прэфікс для іх:
197193
198194
<Sandpack>
199195
@@ -204,10 +200,10 @@ export default function Form() {
204200
const id = useId();
205201
return (
206202
<form>
207-
<label htmlFor={id + '-firstName'}>First Name:</label>
203+
<label htmlFor={id + '-firstName'}>Імя:</label>
208204
<input id={id + '-firstName'} type="text" />
209205
<hr />
210-
<label htmlFor={id + '-lastName'}>Last Name:</label>
206+
<label htmlFor={id + '-lastName'}>Прозвішча:</label>
211207
<input id={id + '-lastName'} type="text" />
212208
</form>
213209
);
@@ -220,20 +216,20 @@ input { margin: 5px; }
220216
221217
</Sandpack>
222218
223-
This lets you avoid calling `useId` for every single element that needs a unique ID.
219+
Гэта дазволіць вам пазбегнуць выклікаў `useId` для кожнага элемента, які патрабуе ўнікальны ідэнтыфікатар.
224220
225221
---
226222
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*/}
228224
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` ідэнтыфікатар будзе пачынацца з адрознага прэфікса, які вы ўказалі.
230226
231227
<Sandpack>
232228
233229
```html public/index.html
234230
<!DOCTYPE html>
235231
<html>
236-
<head><title>My app</title></head>
232+
<head><title>Мая праграма</title></head>
237233
<body>
238234
<div id="root1"></div>
239235
<div id="root2"></div>
@@ -246,18 +242,18 @@ import { useId } from 'react';
246242

247243
function PasswordField() {
248244
const passwordHintId = useId();
249-
console.log('Generated identifier:', passwordHintId)
245+
console.log('Згенераваны ідэнтыфікатар:', passwordHintId)
250246
return (
251247
<>
252248
<label>
253-
Password:
249+
Пароль:
254250
<input
255251
type="password"
256252
aria-describedby={passwordHintId}
257253
/>
258254
</label>
259255
<p id={passwordHintId}>
260-
The password should contain at least 18 characters
256+
Пароль мусіць змяшчаць як мінімум 18 сімвалаў
261257
</p>
262258
</>
263259
);
@@ -266,7 +262,7 @@ function PasswordField() {
266262
export default function App() {
267263
return (
268264
<>
269-
<h2>Choose password</h2>
265+
<h2>Прыдумайце пароль</h2>
270266
<PasswordField />
271267
</>
272268
);
@@ -309,9 +305,9 @@ input { margin: 5px; }
309305
310306
---
311307
312-
### 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*/}
313309
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)
315311
316312
```js
317313
// Server
@@ -335,4 +331,4 @@ const root = hydrateRoot(
335331
);
336332
```
337333
338-
You do not need to pass `identifierPrefix` if you only have one React app on the page.
334+
У `identifierPrefix` няма патрэбы, калі вы маеце толькі адну праграму React на старонцы.

0 commit comments

Comments
 (0)