` syntax:](/reference/react/Fragment#rendering-a-list-of-fragments)
```js
import { Fragment } from 'react';
@@ -393,46 +393,46 @@ const listItems = people.map(person =>
);
```
-Fragments disappear from the DOM, so this will produce a flat list of ``, `
`, `
`, `
`, and so on.
+I Fragment scompaiono dal DOM, quindi questo produrrà una lista piatta di `
`, `
`, `
`, `
`, e così via.
-### Where to get your `key` {/*where-to-get-your-key*/}
+### Da dove prendere la `key` {/*where-to-get-your-key*/}
+Diverse fonti di dati forniscono diverse fonti di key:
-Different sources of data provide different sources of keys:
-* **Data from a database:** If your data is coming from a database, you can use the database keys/IDs, which are unique by nature.
-* **Locally generated data:** If your data is generated and persisted locally (e.g. notes in a note-taking app), use an incrementing counter, [`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID) or a package like [`uuid`](https://www.npmjs.com/package/uuid) when creating items.
+* **Dati provenienti da un database:** Se i tuoi dati provengono da un database, puoi usare le chiavi / ID del database, che sono uniche per natura.
+* **Dati generati localmente:** Se i tuoi dati sono generati e mantenuti localmente (ad esempio note in un'app per prendere appunti), usa un contatore crescente, [`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID) o un pacchetto come [`uuid`](https://www.npmjs.com/package/uuid) quando crei gli elementi.
-### Rules of keys {/*rules-of-keys*/}
+### Regole delle key {/*rules-of-keys*/}
-* **Keys must be unique among siblings.** However, it’s okay to use the same keys for JSX nodes in _different_ arrays.
-* **Keys must not change** or that defeats their purpose! Don't generate them while rendering.
+* **Le key devono essere uniche tra i loro simili.** Tuttavia, è possibile utilizzare le stesse key per i nodi JSX in array _diversi_.
+* **Le key non devono cambiare** o questo ne annulla lo scopo! Non generarle durante il rendering.
-### Why does React need keys? {/*why-does-react-need-keys*/}
+### Perchè React ha bisogno delle key? {/*why-does-react-need-keys*/}
-Imagine that files on your desktop didn't have names. Instead, you'd refer to them by their order -- the first file, the second file, and so on. You could get used to it, but once you delete a file, it would get confusing. The second file would become the first file, the third file would be the second file, and so on.
+Immagina se i file sul tuo desktop non avessero nomi. Al contrario, ti riferiresti a loro in base al loro ordine: il primo file, il secondo file e così via. Potresti abituarti, ma una volta eliminato un file, sarebbe confuso. Il secondo file diventerebbe il primo file, il terzo file sarebbe il secondo file e così via.
-File names in a folder and JSX keys in an array serve a similar purpose. They let us uniquely identify an item between its siblings. A well-chosen key provides more information than the position within the array. Even if the _position_ changes due to reordering, the `key` lets React identify the item throughout its lifetime.
+I nomi dei file in una cartella e le key JSX in un array servono a uno scopo simile. Ci consentono di identificare univocamente un elemento tra i suoi simili. Una key ben scelta fornisce più informazioni rispetto alla posizione all'interno dell'array. Anche se la _posizione_ cambia a causa del riordinamento, la `key` consente a React di identificare l'elemento per tutta la sua durata.
-You might be tempted to use an item's index in the array as its key. In fact, that's what React will use if you don't specify a `key` at all. But the order in which you render items will change over time if an item is inserted, deleted, or if the array gets reordered. Index as a key often leads to subtle and confusing bugs.
+Potresti essere tentato di usare l'indice di un elemento nell'array come sua key. In realtà, è quello che React userà se non specifici una `key` affatto. Ma l'ordine in cui renderizzi gli elementi cambierà nel tempo se un elemento viene inserito, eliminato o se l'array viene riordinato. L'indice come chiave spesso porta a bug impercettibili e confusi.
-Similarly, do not generate keys on the fly, e.g. with `key={Math.random()}`. This will cause keys to never match up between renders, leading to all your components and DOM being recreated every time. Not only is this slow, but it will also lose any user input inside the list items. Instead, use a stable ID based on the data.
+Similmente, non generare le key al volo, ad esempio con `key={Math.random()}`. Questo farà sì che le chiavi non corrispondano mai tra i render, portando a tutti i tuoi componenti e DOM che vengono ricreati ogni volta. Non solo questo è lento, ma perderà anche qualsiasi input dell'utente all'interno degli elementi della lista. Invece, usa un ID stabile basato sui dati.
-Note that your components won't receive `key` as a prop. It's only used as a hint by React itself. If your component needs an ID, you have to pass it as a separate prop: ``.
+Nota che il tuo componente non riceverà `key` come prop. Viene utilizzato solo come suggerimento da React stesso. Se il tuo componente ha bisogno di un ID, devi passarlo come prop separata: ``.
-On this page you learned:
+In questa pagina hai imparato:
-* How to move data out of components and into data structures like arrays and objects.
-* How to generate sets of similar components with JavaScript's `map()`.
-* How to create arrays of filtered items with JavaScript's `filter()`.
-* Why and how to set `key` on each component in a collection so React can keep track of each of them even if their position or data changes.
+* Come muovere i dati fuori dai componenti e in strutture dati come array e oggetti.
+* Come generare una lista componenti simili con `map()` di JavaScript.
+* Come creare array di elementi filtrati con `filter()` di JavaScript.
+* Il perchè e il come impostare `key` su ogni componente in una collezione in modo che React possa tener traccia di ognuno di essi anche se la loro posizione o i dati cambiano.
@@ -440,11 +440,11 @@ On this page you learned:
-#### Splitting a list in two {/*splitting-a-list-in-two*/}
+#### Dividere una lista in due {/*splitting-a-list-in-two*/}
-This example shows a list of all people.
+Questo esempio mostra una lista di tutte le persone.
+Cambialo in modo da mostrare due liste separate una dopo l'altra: **Chemists** e **Everyone Else.**. Come in precedenza, puoi determinare se una persona è un chimico controllando se `person.profession === 'chemist'`.
-Change it to show two separate lists one after another: **Chemists** and **Everyone Else.** Like previously, you can determine whether a person is a chemist by checking if `person.profession === 'chemist'`.
@@ -535,7 +535,7 @@ img { width: 100px; height: 100px; border-radius: 50%; }
-You could use `filter()` twice, creating two separate arrays, and then `map` over both of them:
+Potresti usare `filter()` due volte per creare due array separati, e poi `map` su entrambi:
@@ -648,9 +648,10 @@ img { width: 100px; height: 100px; border-radius: 50%; }
-In this solution, the `map` calls are placed directly inline into the parent `` elements, but you could introduce variables for them if you find that more readable.
+In questa soluzione, il `map` è inserito direttamente nei tag `` genitori, ma potresti anche introdurre delle variabili se lo trovi più leggibile.
-There is still a bit duplication between the rendered lists. You can go further and extract the repetitive parts into a `` component:
+
+Come puoi vedere, questa soluzione è un po' ripetitiva. Puoi andare oltre e estrarre le parti ripetitive in un componente ``:
@@ -762,9 +763,9 @@ img { width: 100px; height: 100px; border-radius: 50%; }
-A very attentive reader might notice that with two `filter` calls, we check each person's profession twice. Checking a property is very fast, so in this example it's fine. If your logic was more expensive than that, you could replace the `filter` calls with a loop that manually constructs the arrays and checks each person once.
+Un lettore molto attento potrebbe notare che con due chiamate `filter`, controlliamo la professione di ogni persona due volte. Controllare una proprietà è molto veloce, quindi in questo esempio va bene. Se la tua logica fosse più costosa di così, potresti sostituire le chiamate `filter` con un ciclo che costruisce manualmente gli array e controlla ogni persona una volta sola.
-In fact, if `people` never change, you could move this code out of your component. From React's perspective, all that matters is that you give it an array of JSX nodes in the end. It doesn't care how you produce that array:
+Inoltre, se `people` non cambia mai, potresti spostare questo codice fuori dal componente. Dal punto di vista di React, l'unica cosa che conta è che alla fine gli dai un array di nodi JSX. Non importa come produci quell'array:
@@ -882,13 +883,13 @@ img { width: 100px; height: 100px; border-radius: 50%; }
-#### Nested lists in one component {/*nested-lists-in-one-component*/}
+#### Liste annidate in un componente {/*nested-lists-in-one-component*/}
-Make a list of recipes from this array! For each recipe in the array, display its name as an `` and list its ingredients in a ``.
+Crea una lista di ricette da questo array! Per ogni ricetta nell'array, visualizza il suo nome come `` e elenca i suoi ingredienti in un ``.
-This will require nesting two different `map` calls.
+Qui abbiamo bisogno di due chiamate a `map` annidate.
@@ -926,7 +927,7 @@ export const recipes = [{
-Here is one way you could go about it:
+Potresti procedere così:
@@ -972,13 +973,13 @@ export const recipes = [{
-Each of the `recipes` already includes an `id` field, so that's what the outer loop uses for its `key`. There is no ID you could use to loop over ingredients. However, it's reasonable to assume that the same ingredient won't be listed twice within the same recipe, so its name can serve as a `key`. Alternatively, you could change the data structure to add IDs, or use index as a `key` (with the caveat that you can't safely reorder ingredients).
+Ogni `recipe` nell'array ha già un campo `id`, quindi è quello che il ciclo esterno usa per il suo `key`. Non c'è nessun ID che potresti usare per iterare sugli ingredienti. Tuttavia, è ragionevole supporre che lo stesso ingrediente non sarà elencato due volte all'interno della stessa ricetta, quindi il suo nome può servire come `key`. In alternativa, potresti cambiare la struttura dei dati per aggiungere gli ID, o usare l'indice come `key` (con il caveat che non puoi riordinare gli ingredienti in modo sicuro).
-#### Extracting a list item component {/*extracting-a-list-item-component*/}
+#### Estrarre un componente elemento di lista {/*extracting-a-list-item-component*/}
-This `RecipeList` component contains two nested `map` calls. To simplify it, extract a `Recipe` component from it which will accept `id`, `name`, and `ingredients` props. Where do you place the outer `key` and why?
+Questo componente `RecipeList` contiene due chiamate `map` annidate. Per semplificarlo, estrai un componente `Recipe` da esso che accetterà le props `id`, `name` e `ingredients`. Dove posizioneresti la `key` esterna e perché?
@@ -1026,7 +1027,7 @@ export const recipes = [{
-You can copy-paste the JSX from the outer `map` into a new `Recipe` component and return that JSX. Then you can change `recipe.name` to `name`, `recipe.id` to `id`, and so on, and pass them as props to the `Recipe`:
+Puoi copia-incollare il JSX dal `map` esterno in un nuovo componente `Recipe` e restituire quel JSX. Quindi puoi cambiare `recipe.name` in `name`, `recipe.id` in `id`, e così via, e passarli come props al `Recipe`:
@@ -1078,15 +1079,15 @@ export const recipes = [{
-Here, `` is a syntax shortcut saying "pass all properties of the `recipe` object as props to the `Recipe` component". You could also write each prop explicitly: ``.
+In questo caso, `` è una shortcut sintattica che dice "passa tutte le proprietà dell'oggetto `recipe` come props al componente `Recipe`". Puoi anche scrivere ogni prop esplicitamente: ``.
-**Note that the `key` is specified on the `` itself rather than on the root `` returned from `Recipe`.** This is because this `key` is needed directly within the context of the surrounding array. Previously, you had an array of `
`s so each of them needed a `key`, but now you have an array of `
`s. In other words, when you extract a component, don't forget to leave the `key` outside the JSX you copy and paste.
+**Nota che la `key` è specificata sul `` stesso piuttosto che sul `` alla base ritornato da `Recipe`.** Questo perché questa `key` è necessaria direttamente nel contesto dell'array circostante. In precedenza, avevi un array di `
` quindi ognuno di loro aveva bisogno di una `key`, ma ora hai un array di `
`. In altre parole, quando estrai un componente, non dimenticare di lasciare la `key` fuori dal JSX che copi e incolli.
-#### List with a separator {/*list-with-a-separator*/}
+#### Lista con un separatore {/*list-with-a-separator*/}
-This example renders a famous haiku by Katsushika Hokusai, with each line wrapped in a `` tag. Your job is to insert an `
` separator between each paragraph. Your resulting structure should look like this:
+Questo esempio renderizza un famoso haiku di Katsushika Hokusai, con ogni riga avvolta in un tag ``. Il tuo compito è inserire un separatore `
` tra ogni paragrafo. La tua struttura risultante dovrebbe assomigliare a questa:
```js
@@ -1098,7 +1099,7 @@ This example renders a famous haiku by Katsushika Hokusai, with each line wrappe
```
-A haiku only contains three lines, but your solution should work with any number of lines. Note that `
` elements only appear *between* the `` elements, not in the beginning or the end!
+Un haiku contiene solo tre righe, ma la tua soluzione dovrebbe funzionare con qualsiasi numero di righe. Nota che gli elementi `
` appaiono solo *tra* gli elementi ``, non all'inizio o alla fine!
@@ -1141,17 +1142,17 @@ hr {
-(This is a rare case where index as a key is acceptable because a poem's lines will never reorder.)
+(Questo è un raro caso in cui l'indice come key è accettabile perché le righe di una poesia non si riordineranno mai.)
-You'll either need to convert `map` to a manual loop, or use a fragment.
+Dovrai convertire `map` in un loop manuale o utilizzare un frammento.
-You can write a manual loop, inserting `
` and `...
` into the output array as you go:
+Puoi scrivere un loop manuale, inserendo `
` e `...
` nell'array di output come di seguito:
@@ -1206,9 +1207,9 @@ hr {
-Using the original line index as a `key` doesn't work anymore because each separator and paragraph are now in the same array. However, you can give each of them a distinct key using a suffix, e.g. `key={i + '-text'}`.
+Se usi l'indice originale come `key` non funziona più perché ogni separatore e paragrafo sono ora nello stesso array. Tuttavia, puoi dare a ciascuno di essi una key distinta usando un suffisso, ad esempio `key={i + '-text'}`.
-Alternatively, you could render a collection of fragments which contain `
` and `...
`. However, the `<>...>` shorthand syntax doesn't support passing keys, so you'd have to write `` explicitly:
+In alternativa, potresti renderizzare una collezione di fragments che contengono `
` e `...
`. Tuttavia, la sintassi abbreviata `<>...>` non supporta il passaggio di key, quindi dovresti scrivere `` esplicitamente:
@@ -1254,7 +1255,7 @@ hr {
-Remember, fragments (often written as `<> >`) let you group JSX nodes without adding extra ``s!
+Ricorda, i fragment (spesso scritti come `<>...>`) ti consentono di raggruppare i nodi JSX senza aggiungere extra `
`!