Skip to content

Translated into Ukrainian list-and-keys #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 19, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 48 additions & 47 deletions content/docs/lists-and-keys.md
Original file line number Diff line number Diff line change
@@ -1,30 +1,30 @@
---
id: lists-and-keys
title: Lists and Keys
title: Списки та ключі
permalink: docs/lists-and-keys.html
prev: conditional-rendering.html
next: forms.html
---

First, let's review how you transform lists in JavaScript.
Спочатку давайте згадаємо, як перетворити списки у JavaScript.

Given the code below, we use the [`map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) function to take an array of `numbers` and double their values. We assign the new array returned by `map()` to the variable `doubled` and log it:
У коді, наведеному нижче, ми використовуємо функцію [`map()`](https://developer.mozilla.org/uk/docs/Web/JavaScript/Reference/Global_Objects/Array/map), щоб подвоїти значення в масиві `numbers`. Ми призначаємо новий масив, що повертається з `map()` до змінної `doubled` і виводимо її в консоль:

```javascript{2}
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((number) => number * 2);
console.log(doubled);
```

This code logs `[2, 4, 6, 8, 10]` to the console.
Цей код виведе `[2, 4, 6, 8, 10]` у консоль.

In React, transforming arrays into lists of [elements](/docs/rendering-elements.html) is nearly identical.
У React, перетворення масивів у список [елементів](/docs/rendering-elements.html) майже ідентичне.

### Rendering Multiple Components {#rendering-multiple-components}
### Рендеринг декількох компонентів {#rendering-multiple-components}

You can build collections of elements and [include them in JSX](/docs/introducing-jsx.html#embedding-expressions-in-jsx) using curly braces `{}`.
Ви можете створити колекції елементів і [вбудувати їх у JSX](/docs/introducing-jsx.html#embedding-expressions-in-jsx) за допомогою фігурних дужок `{}`.

Below, we loop through the `numbers` array using the JavaScript [`map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) function. We return a `<li>` element for each item. Finally, we assign the resulting array of elements to `listItems`:
Нижче, пройдемо по масиву `numbers` використовуючи функцію JavaScript [`map()`](https://developer.mozilla.org/uk/docs/Web/JavaScript/Reference/Global_Objects/Array/map), і повернемо елемент `<li>` у кожній ітерації. Нарешті, одержаний масив елементів збережемо у `listItems`:

```javascript{2-4}
const numbers = [1, 2, 3, 4, 5];
Expand All @@ -33,7 +33,7 @@ const listItems = numbers.map((number) =>
);
```

We include the entire `listItems` array inside a `<ul>` element, and [render it to the DOM](/docs/rendering-elements.html#rendering-an-element-into-the-dom):
Тепер ми включимо масив `listItems` цілком всередину елемента `<ul>`, і [будемо рендерити його у DOM](/docs/rendering-elements.html#rendering-an-element-into-the-dom):

```javascript{2}
ReactDOM.render(
Expand All @@ -42,15 +42,15 @@ ReactDOM.render(
);
```

[**Try it on CodePen**](https://codepen.io/gaearon/pen/GjPyQr?editors=0011)
[**Спробуйте на CodePen**](https://codepen.io/gaearon/pen/GjPyQr?editors=0011)

This code displays a bullet list of numbers between 1 and 5.
Цей код виведе маркований список чисел від 1 до 5.

### Basic List Component {#basic-list-component}
### Простий компонент-список {#basic-list-component}

Usually you would render lists inside a [component](/docs/components-and-props.html).
Зазвичай, ви будете рендерити списки всередині якогось [компонента](/docs/components-and-props.html).

We can refactor the previous example into a component that accepts an array of `numbers` and outputs a list of elements.
Ми можемо відрефакторити попередній приклад з використанням компонента, котрий приймає масив `numbers` та виводить невпорядкований список елементів.

```javascript{3-5,7,13}
function NumberList(props) {
Expand All @@ -70,9 +70,9 @@ ReactDOM.render(
);
```

When you run this code, you'll be given a warning that a key should be provided for list items. A "key" is a special string attribute you need to include when creating lists of elements. We'll discuss why it's important in the next section.
Коли ви запустите цей код, ви отримаєте попередження, що для елементів списку має бути вказано ключ. "Ключ" - це спеціальний рядковий атрибут, який потрібно вказувати при створенні списку елементів. Ми обговоримо, чому це важливо, у наступній секції.

Let's assign a `key` to our list items inside `numbers.map()` and fix the missing key issue.
Щоб виправити проблему з невказаними ключами, додамо нашим елементам `key` атрибут списку всередині `numbers.map()`.

```javascript{4}
function NumberList(props) {
Expand All @@ -94,11 +94,11 @@ ReactDOM.render(
);
```

[**Try it on CodePen**](https://codepen.io/gaearon/pen/jrXYRR?editors=0011)
[**Спробуйте на CodePen**](https://codepen.io/gaearon/pen/jrXYRR?editors=0011)

## Keys {#keys}
## Ключі {#keys}

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity:
Ключі допомагають React визначити, які елементи були змінені, додані або видалені. Ключі повинні бути надані елементам всередині масиву, щоб надати елементам стабільну ідентичність:

```js{3}
const numbers = [1, 2, 3, 4, 5];
Expand All @@ -109,7 +109,7 @@ const listItems = numbers.map((number) =>
);
```

The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys:
Найкращий спосіб вибрати ключ - це використати рядок, котрий буде вочевидь відрізняти елемент списку від його сусідів. Найчастіше ви будете використовувати ID з ваших даних як ключі:

```js{2}
const todoItems = todos.map((todo) =>
Expand All @@ -119,34 +119,34 @@ const todoItems = todos.map((todo) =>
);
```

When you don't have stable IDs for rendered items, you may use the item index as a key as a last resort:
Якщо у вас немає стабільних ID для відрендерених елементів, то в крайньому випадку можна використовувати індекс елемента як ключ:

```js{2,3}
const todoItems = todos.map((todo, index) =>
// Only do this if items have no stable IDs
// Робіть так, тільки якщо у елементів масиву немає заданого ID
<li key={index}>
{todo.text}
</li>
);
```

We don't recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state. Check out Robin Pokorny's article for an [in-depth explanation on the negative impacts of using an index as a key](https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318). If you choose not to assign an explicit key to list items then React will default to using indexes as keys.
Ми не рекомендуємо використовувати індекси для ключів, якщо порядок елементів може змінюватися. Це може негативно вплинути на продуктивність та може викликати проблеми зі станом компонента. Почитайте статтю Робіна Покорни (Robin Pokorny), [яка досконало пояснює, чому індекси-ключі призводять до проблем](https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318). Якщо ви вирішите не призначити ключ для елемента в списку, то React за замовчуванням буде використовувати індекси як ключі.

Here is an [in-depth explanation about why keys are necessary](/docs/reconciliation.html#recursing-on-children) if you're interested in learning more.
Якщо ви зацікавлені в отриманні додаткової інформації - ось [детальне пояснення того, чому ключі необхідні](/docs/reconciliation.html#recursing-on-children).

### Extracting Components with Keys {#extracting-components-with-keys}
### Вилучення компонентів з ключами {#extracting-components-with-keys}

Keys only make sense in the context of the surrounding array.
Ключі необхідно визначати безпосередньо всередині масивів.

For example, if you [extract](/docs/components-and-props.html#extracting-components) a `ListItem` component, you should keep the key on the `<ListItem />` elements in the array rather than on the `<li>` element in the `ListItem` itself.
Наприклад, якщо ви [витягаєте](/docs/components-and-props.html#extracting-components) компонент `ListItem`, то потрібно вказувати ключ для `<ListItem />` елементів в масиві замість елемента `<li>` всередині самого `ListItem`.

**Example: Incorrect Key Usage**
**Приклад невірного використання ключів**

```javascript{4,5,14,15}
function ListItem(props) {
const value = props.value;
return (
// Wrong! There is no need to specify the key here:
// Невірно! Немає необхідності визначати тут ключ:
<li key={value.toString()}>
{value}
</li>
Expand All @@ -156,7 +156,7 @@ function ListItem(props) {
function NumberList(props) {
const numbers = props.numbers;
const listItems = numbers.map((number) =>
// Wrong! The key should have been specified here:
// Невірно! Ключ необхідно визначити тут:
<ListItem value={number} />
);
return (
Expand All @@ -173,18 +173,18 @@ ReactDOM.render(
);
```

**Example: Correct Key Usage**
**Приклад вірного використання ключів**

```javascript{2,3,9,10}
function ListItem(props) {
// Correct! There is no need to specify the key here:
// Вірно! Тут не потрібно визначати ключ:
return <li>{props.value}</li>;
}

function NumberList(props) {
const numbers = props.numbers;
const listItems = numbers.map((number) =>
// Correct! Key should be specified inside the array.
// Вірно! Ключ потрібно визначати всередині масиву:
<ListItem key={number.toString()}
value={number} />
);
Expand All @@ -202,13 +202,13 @@ ReactDOM.render(
);
```

[**Try it on CodePen**](https://codepen.io/gaearon/pen/ZXeOGM?editors=0010)
[**Спробуйте на CodePen**](https://codepen.io/gaearon/pen/ZXeOGM?editors=0010)

A good rule of thumb is that elements inside the `map()` call need keys.
Елементам усередині `map()` зазвичай потрібні ключі.

### Keys Must Only Be Unique Among Siblings {#keys-must-only-be-unique-among-siblings}
### Ключі повинні бути унікальними лише між сусідніх елементів {#keys-must-only-be-unique-among-siblings}

Keys used within arrays should be unique among their siblings. However they don't need to be globally unique. We can use the same keys when we produce two different arrays:
Ключі, що використовуються в масивах, повинні бути унікальними тільки серед своїх сусідніх елементів. Однак їм не потрібно бути унікальними глобально. Можна використовувати той самий ключ в двох різних масивах:

```js{2,5,11,12,19,21}
function Blog(props) {
Expand Down Expand Up @@ -237,18 +237,18 @@ function Blog(props) {
}

const posts = [
{id: 1, title: 'Hello World', content: 'Welcome to learning React!'},
{id: 2, title: 'Installation', content: 'You can install React from npm.'}
{id: 1, title: 'Привіт, світ', content: 'Ласкаво просимо до вивчення React!'},
{id: 2, title: 'Установка', content: 'React можна встановити через npm.'}
];
ReactDOM.render(
<Blog posts={posts} />,
document.getElementById('root')
);
```

[**Try it on CodePen**](https://codepen.io/gaearon/pen/NRZYGN?editors=0010)
[**Спробуйте на CodePen**](https://codepen.io/gaearon/pen/NRZYGN?editors=0010)

Keys serve as a hint to React but they don't get passed to your components. If you need the same value in your component, pass it explicitly as a prop with a different name:
Ключі слугують підказками для React, але вони ніколи не передаються до ваших компонентів. Якщо в компоненті потрібно те ж саме значення, то передайте його явно через проп з іншим ім'ям:

```js{3,4}
const content = posts.map((post) =>
Expand All @@ -259,11 +259,11 @@ const content = posts.map((post) =>
);
```

With the example above, the `Post` component can read `props.id`, but not `props.key`.
У наведеному вище прикладі компонент `Post` може прочитати значення `props.id`, але не `props.key`.

### Embedding map() in JSX {#embedding-map-in-jsx}
### Вбудовування map() у JSX {#embedding-map-in-jsx}

In the examples above we declared a separate `listItems` variable and included it in JSX:
У прикладах вище ми оголосили окрему змінну `listItems` та вставили її у JSX:

```js{3-6}
function NumberList(props) {
Expand All @@ -280,7 +280,8 @@ function NumberList(props) {
}
```

JSX allows [embedding any expression](/docs/introducing-jsx.html#embedding-expressions-in-jsx) in curly braces so we could inline the `map()` result:
JSX дозволяє [вбудувати будь-який вираз](/docs/introducing-jsx.html#embedding-expressions-in-jsx) у фігурні дужки, щоб ми зуміли включити результат виконання `map()`:


```js{5-8}
function NumberList(props) {
Expand All @@ -296,6 +297,6 @@ function NumberList(props) {
}
```

[**Try it on CodePen**](https://codepen.io/gaearon/pen/BLvYrB?editors=0010)
[**Спробуйте на CodePen**](https://codepen.io/gaearon/pen/BLvYrB?editors=0010)

Sometimes this results in clearer code, but this style can also be abused. Like in JavaScript, it is up to you to decide whether it is worth extracting a variable for readability. Keep in mind that if the `map()` body is too nested, it might be a good time to [extract a component](/docs/components-and-props.html#extracting-components).
Іноді це призводить до більш чистого коду, але буває і навпаки. Як і в будь-якому JavaScript-коді, вам доведеться самостійно вирішувати, чи варто витягати код в змінну заради читабельності. Майте на увазі, що якщо код всередині `map()` занадто громіздкий, має сенс [витягти його в окремий компонент](/docs/components-and-props.html#extracting-components).