Skip to content

Commit e85f709

Browse files
authored
Merge pull request #633 from LeoMorgan113/translation/useId
docs: translation for useId page
2 parents 40e76e1 + 717643a commit e85f709

File tree

2 files changed

+52
-51
lines changed

2 files changed

+52
-51
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ node_modules
1111
# next.js
1212
/.next/
1313
/out/
14+
.idea
1415

1516
# production
1617
/build

src/content/reference/react/useId.md

Lines changed: 51 additions & 51 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` — це хук для генерації унікальних ідентифікаторів (_далі_ — ID), які можуть передаватися як атрибути доступності.
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` на верхньому рівні вашого компонента, щоб згенерувати унікальне ID:
2424

2525
```js
2626
import { useId } from 'react';
@@ -30,37 +30,37 @@ 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` повертає унікальну ID-стрічку, пов'язану з конкретним запитом `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` — це хук, тож він може викликатися тільки **на верхньому рівні вашого компонента** або у ваших власних хуках. Ви не можете викликати його в циклах або умовно. Якщо ж є така потреба, то виокреміть новий компонент та перемістіть у нього стан.
4646
47-
* `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)
47+
* `useId` **не має використовуватися для генерації ключів** у списках. [Ключі мають генеруватися з ваших даних.](/learn/rendering-lists#where-to-get-your-key)
4848
49-
* `useId` currently cannot be used in [async Server Components](/reference/rsc/server-components#async-components-with-server-components).
49+
* `useId` наразі не може бути використано в [асинхронних серверних компонентах](/reference/rsc/server-components#async-components-with-server-components).
5050
5151
---
5252
53-
## Usage {/*usage*/}
53+
## Використання {/*usage*/}
5454
5555
<Pitfall>
5656
57-
**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)
57+
**Не викликайте `useId` для генерації ключів у списку.** [Ключі мають генеруватися з ваших даних.](/learn/rendering-lists#where-to-get-your-key)
5858
5959
</Pitfall>
6060
61-
### Generating unique IDs for accessibility attributes {/*generating-unique-ids-for-accessibility-attributes*/}
61+
### Генерація унікальних ID для атрибутів доступності {/*generating-unique-ids-for-accessibility-attributes*/}
6262
63-
Call `useId` at the top level of your component to generate a unique ID:
63+
Викличте `useId` на верхньому рівні вашого компонента для генерації унікального ID:
6464
6565
```js [[1, 4, "passwordHintId"]]
6666
import { useId } from 'react';
@@ -70,7 +70,7 @@ function PasswordField() {
7070
// ...
7171
```
7272
73-
You can then pass the <CodeStep step={1}>generated ID</CodeStep> to different attributes:
73+
Далі ви можете передати <CodeStep step={1}>згенерований ID</CodeStep> до різних атрибутів:
7474
7575
```js [[1, 2, "passwordHintId"], [1, 3, "passwordHintId"]]
7676
<>
@@ -79,11 +79,11 @@ You can then pass the <CodeStep step={1}>generated ID</CodeStep> to different at
7979
</>
8080
```
8181
82-
**Let's walk through an example to see when this is useful.**
82+
**Розглянемо приклади, коли це може бути корисно.**
8383
84-
[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).
84+
[Атрибути доступності 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), дають змогу зазначити, що два теги пов'язані один з одним. Наприклад, ви можете зазначити, що елемент (як-от input) описаний іншим компонентом (як-от параграф).
8585
86-
In regular HTML, you would write it like this:
86+
У звичайному HTML ви б написали наступне:
8787
8888
```html {5,8}
8989
<label>
@@ -94,11 +94,11 @@ In regular HTML, you would write it like this:
9494
/>
9595
</label>
9696
<p id="password-hint">
97-
The password should contain at least 18 characters
97+
Довжина паролю має бути не менш ніж 18 символів
9898
</p>
9999
```
100100
101-
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`:
101+
Однак, таке задання ID не найкраща практика в React. Компонент може бути відрендерений на сторінці більш ніж один раз — і ID повинні бути унікальні! Замість незмінно заданих ID, згенеруйте унікальне значення за допомогою `useId`:
102102
103103
```js {4,11,14}
104104
import { useId } from 'react';
@@ -115,14 +115,14 @@ function PasswordField() {
115115
/>
116116
</label>
117117
<p id={passwordHintId}>
118-
The password should contain at least 18 characters
118+
Довжина паролю має бути не менш ніж 18 символів
119119
</p>
120120
</>
121121
);
122122
}
123123
```
124124
125-
Now, even if `PasswordField` appears multiple times on the screen, the generated IDs won't clash.
125+
Тож, навіть якщо `PasswordField` з'явиться на сторінці багато разів, згенеровані ID не конфліктуватимуть.
126126
127127
<Sandpack>
128128
@@ -141,7 +141,7 @@ function PasswordField() {
141141
/>
142142
</label>
143143
<p id={passwordHintId}>
144-
The password should contain at least 18 characters
144+
Довжина паролю має бути не менш ніж 18 символів
145145
</p>
146146
</>
147147
);
@@ -150,9 +150,9 @@ function PasswordField() {
150150
export default function App() {
151151
return (
152152
<>
153-
<h2>Choose password</h2>
153+
<h2>Введіть пароль</h2>
154154
<PasswordField />
155-
<h2>Confirm password</h2>
155+
<h2>Підтвердіть пароль</h2>
156156
<PasswordField />
157157
</>
158158
);
@@ -165,33 +165,33 @@ input { margin: 5px; }
165165
166166
</Sandpack>
167167
168-
[Watch this video](https://www.youtube.com/watch?v=0dNzNcuEuOo) to see the difference in the user experience with assistive technologies.
168+
[Перегляньте відео](https://www.youtube.com/watch?v=0dNzNcuEuOo), щоб побачити різницю користувацького досвіду з допоміжними технологіями.
169169
170170
<Pitfall>
171171
172-
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.
172+
Для [серверного рендерингу](/reference/react-dom/server), **`useId` потребує ідентичного дерева компонентів на сервері та на клієнті**. Якщо дерева, які ви рендерите на сервері та на клієнті, не збігаються, то і згенеровані ID не будуть збігатись.
173173
174174
</Pitfall>
175175
176176
<DeepDive>
177177
178-
#### Why is useId better than an incrementing counter? {/*why-is-useid-better-than-an-incrementing-counter*/}
178+
#### Чому використання useId краще за інкрементний лічильник? {/*why-is-useid-better-than-an-incrementing-counter*/}
179179
180-
You might be wondering why `useId` is better than incrementing a global variable like `nextId++`.
180+
Можливо, вам кортить дізнатися, чому використання `useId` краще за інкрементування глобальної змінної, як наприклад, `nextId++`.
181181
182-
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.
182+
Початкова перевага `useId` в тому, що React запевниться, що це працює разом із [серверним рендерингом.](/reference/react-dom/server) Протягом серверного рендерингу, ваш компонент генерує HTML-вивід. Далі на клієнті [гідрація](/reference/react-dom/client/hydrateRoot) прикріплює обробники подій до згенерованого HTML. Для коректної роботи гідрації клієнтський вивід має збігатись із серверним HTML.
183183
184-
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.
184+
Це складно гарантувати для інкрементного лічильника, бо порядок, за яким клієнтські компоненти проходять гідрацію, не збігається з порядком, за яким був виданий серверний HTML. Викликаючи `useId`, ви запевняєтеся, що гідрація буде працювати, а серверний і клієнтський виводи будуть збігатися.
185185
186-
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.
186+
У межах React, `useId` генерується з "батьківського шляху" компонента, що його викликав. Ось чому, якщо клієнтське та серверне дерево однакове, "батьківський шлях" буде збігатися, незважаючи на порядок рендерингу.
187187
188188
</DeepDive>
189189
190190
---
191191
192-
### Generating IDs for several related elements {/*generating-ids-for-several-related-elements*/}
192+
### Генерація ID для декількох пов'язаних елементів {/*generating-ids-for-several-related-elements*/}
193193
194-
If you need to give IDs to multiple related elements, you can call `useId` to generate a shared prefix for them:
194+
Якщо треба додати ID для декількох пов'язаних елементів, ви можете викликати `useId` для генерації спільного префіксу:
195195
196196
<Sandpack>
197197
@@ -202,10 +202,10 @@ export default function Form() {
202202
const id = useId();
203203
return (
204204
<form>
205-
<label htmlFor={id + '-firstName'}>First Name:</label>
206-
<input id={id + '-firstName'} type="text" />
205+
<label htmlFor={id + '-name'}>Ім'я:</label>
206+
<input id={id + '-name'} type="text" />
207207
<hr />
208-
<label htmlFor={id + '-lastName'}>Last Name:</label>
208+
<label htmlFor={id + '-lastName'}>Прізвище:</label>
209209
<input id={id + '-lastName'} type="text" />
210210
</form>
211211
);
@@ -218,20 +218,20 @@ input { margin: 5px; }
218218
219219
</Sandpack>
220220
221-
This lets you avoid calling `useId` for every single element that needs a unique ID.
221+
Це дасть змогу виклику `useId` для кожного окремого елементу, якому треба унікальне ID.
222222
223223
---
224224
225-
### Specifying a shared prefix for all generated IDs {/*specifying-a-shared-prefix-for-all-generated-ids*/}
225+
### Визначення спільного префікса для всіх згенерованих ID {/*specifying-a-shared-prefix-for-all-generated-ids*/}
226226
227-
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.
227+
Якщо ви рендерите декілька незалежних React-застосунків на одній сторінці, передавайте `identifierPrefix` як опцію до вашого [`createRoot`](/reference/react-dom/client/createRoot#parameters) або [`hydrateRoot`](/reference/react-dom/client/hydrateRoot). Це забезпечить те, що ID, згенеровані двома різними застосунками, ніколи не перетнуться, бо кожен ідентифікатор, згенерований за допомогою `useId`, починатиметься з окремого префіксу, який ви вказали.
228228
229229
<Sandpack>
230230
231231
```html public/index.html
232232
<!DOCTYPE html>
233233
<html>
234-
<head><title>My app</title></head>
234+
<head><title>Мій застосунок</title></head>
235235
<body>
236236
<div id="root1"></div>
237237
<div id="root2"></div>
@@ -244,18 +244,18 @@ import { useId } from 'react';
244244
245245
function PasswordField() {
246246
const passwordHintId = useId();
247-
console.log('Generated identifier:', passwordHintId)
247+
console.log('Згенерований ідентифікатор:', passwordHintId)
248248
return (
249249
<>
250250
<label>
251-
Password:
251+
Пароль:
252252
<input
253-
type="password"
253+
type="пароль"
254254
aria-describedby={passwordHintId}
255255
/>
256256
</label>
257257
<p id={passwordHintId}>
258-
The password should contain at least 18 characters
258+
Довжина паролю має бути не менш ніж 18 символів
259259
</p>
260260
</>
261261
);
@@ -264,7 +264,7 @@ function PasswordField() {
264264
export default function App() {
265265
return (
266266
<>
267-
<h2>Choose password</h2>
267+
<h2>Оберіть пароль</h2>
268268
<PasswordField />
269269
</>
270270
);
@@ -307,9 +307,9 @@ input { margin: 5px; }
307307
308308
---
309309
310-
### Using the same ID prefix on the client and the server {/*using-the-same-id-prefix-on-the-client-and-the-server*/}
310+
### Використання однакового ID-префікса на клієнті та сервері {/*using-the-same-id-prefix-on-the-client-and-the-server*/}
311311
312-
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)
312+
Якщо ви [рендерите декілька незалежних 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)
313313
314314
```js
315315
// Server
@@ -333,4 +333,4 @@ const root = hydrateRoot(
333333
);
334334
```
335335
336-
You do not need to pass `identifierPrefix` if you only have one React app on the page.
336+
Немає потреби передавати `identifierPrefix`, якщо ви маєте тільки один React-застосунок на сторінці.

0 commit comments

Comments
 (0)