diff --git a/src/content/learn/manipulating-the-dom-with-refs.md b/src/content/learn/manipulating-the-dom-with-refs.md index 2d1ee8685..a6b794564 100644 --- a/src/content/learn/manipulating-the-dom-with-refs.md +++ b/src/content/learn/manipulating-the-dom-with-refs.md @@ -1,52 +1,52 @@ --- -title: 'Manipulating the DOM with Refs' +title: 'Manipolare il DOM con i Refs' --- -React automatically updates the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model/Introduction) to match your render output, so your components won't often need to manipulate it. However, sometimes you might need access to the DOM elements managed by React--for example, to focus a node, scroll to it, or measure its size and position. There is no built-in way to do those things in React, so you will need a *ref* to the DOM node. +React aggiorna automaticamente il [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model/Introduction) per corrispondere al tuo output di rendering, quindi i tuoi componenti non avranno spesso bisogno di manipolarlo. Tuttavia, a volte potresti aver bisogno di accedere agli elementi DOM gestiti da React--per esempio, per mettere a fuoco un nodo, scorrere fino ad esso o misurarne le dimensioni e la posizione. Non c'è un modo integrato per fare queste cose in React, quindi avrai bisogno di un *ref* al nodo DOM. -- How to access a DOM node managed by React with the `ref` attribute -- How the `ref` JSX attribute relates to the `useRef` Hook -- How to access another component's DOM node -- In which cases it's safe to modify the DOM managed by React +- Come accedere a un nodo DOM gestito da React con l'attributo `ref` +- Come l'attributo JSX `ref` si relaziona all'Hook `useRef` +- Come accedere al nodo DOM di un altro componente +- In quali casi è sicuro modificare il DOM gestito da React -## Getting a ref to the node {/*getting-a-ref-to-the-node*/} +## Ottenere un ref al nodo {/*getting-a-ref-to-the-node*/} -To access a DOM node managed by React, first, import the `useRef` Hook: +Per accedere a un nodo DOM gestito da React, prima importa l'Hook `useRef`: ```js import { useRef } from 'react'; ``` -Then, use it to declare a ref inside your component: +Quindi, usalo per dichiarare un ref all'interno del tuo componente: ```js const myRef = useRef(null); ``` -Finally, pass your ref as the `ref` attribute to the JSX tag for which you want to get the DOM node: +Infine, passa il tuo ref come attributo `ref` al tag JSX per il quale vuoi ottenere il nodo DOM: ```js
``` -The `useRef` Hook returns an object with a single property called `current`. Initially, `myRef.current` will be `null`. When React creates a DOM node for this `
`, React will put a reference to this node into `myRef.current`. You can then access this DOM node from your [event handlers](/learn/responding-to-events) and use the built-in [browser APIs](https://developer.mozilla.org/docs/Web/API/Element) defined on it. +L'Hook `useRef` restituisce un oggetto con una singola proprietà chiamata `current`. Inizialmente, `myRef.current` sarà `null`. Quando React crea un nodo DOM per questo `
`, React metterà un riferimento a questo nodo in `myRef.current`. Potrai quindi accedere a questo nodo DOM dai tuoi [gestori di eventi](/learn/responding-to-events) e usare le [API del browser](https://developer.mozilla.org/docs/Web/API/Element) integrate definite su di esso. ```js -// You can use any browser APIs, for example: +// Puoi usare qualsiasi API del browser, per esempio: myRef.current.scrollIntoView(); ``` -### Example: Focusing a text input {/*example-focusing-a-text-input*/} +### Esempio: Mettere a fuoco un input di testo {/*example-focusing-a-text-input*/} -In this example, clicking the button will focus the input: +In questo esempio, cliccando il pulsante verrà messo a fuoco l'input: @@ -64,7 +64,7 @@ export default function Form() { <> ); @@ -73,18 +73,18 @@ export default function Form() { -To implement this: +Per implementare questo: -1. Declare `inputRef` with the `useRef` Hook. -2. Pass it as ``. This tells React to **put this ``'s DOM node into `inputRef.current`.** -3. In the `handleClick` function, read the input DOM node from `inputRef.current` and call [`focus()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on it with `inputRef.current.focus()`. -4. Pass the `handleClick` event handler to ` ); @@ -408,9 +408,9 @@ export default function MyForm() { -#### Exposing a subset of the API with an imperative handle {/*exposing-a-subset-of-the-api-with-an-imperative-handle*/} +#### Esporre un sottoinsieme dell'API con un handle imperativo {/*exposing-a-subset-of-the-api-with-an-imperative-handle*/} -In the above example, the ref passed to `MyInput` is passed on to the original DOM input element. This lets the parent component call `focus()` on it. However, this also lets the parent component do something else--for example, change its CSS styles. In uncommon cases, you may want to restrict the exposed functionality. You can do that with [`useImperativeHandle`](/reference/react/useImperativeHandle): +Nell'esempio sopra, il ref passato a `MyInput` viene passato all'elemento input DOM originale. Questo permette al componente genitore di chiamare `focus()` su di esso. Tuttavia, questo permette anche al componente genitore di fare qualcos'altro--per esempio, cambiare i suoi stili CSS. In casi non comuni, potresti voler limitare la funzionalità esposta. Puoi farlo con [`useImperativeHandle`](/reference/react/useImperativeHandle): @@ -420,7 +420,7 @@ import { useRef, useImperativeHandle } from "react"; function MyInput({ ref }) { const realInputRef = useRef(null); useImperativeHandle(ref, () => ({ - // Only expose focus and nothing else + // Esponi solo focus e nient'altro focus() { realInputRef.current.focus(); }, @@ -438,7 +438,7 @@ export default function Form() { return ( <> - + ); } @@ -446,28 +446,28 @@ export default function Form() { -Here, `realInputRef` inside `MyInput` holds the actual input DOM node. However, [`useImperativeHandle`](/reference/react/useImperativeHandle) instructs React to provide your own special object as the value of a ref to the parent component. So `inputRef.current` inside the `Form` component will only have the `focus` method. In this case, the ref "handle" is not the DOM node, but the custom object you create inside [`useImperativeHandle`](/reference/react/useImperativeHandle) call. +Qui, `realInputRef` all'interno di `MyInput` contiene il nodo DOM input effettivo. Tuttavia, [`useImperativeHandle`](/reference/react/useImperativeHandle) istruisce React a fornire il tuo oggetto speciale come valore di un ref al componente genitore. Quindi `inputRef.current` all'interno del componente `Form` avrà solo il metodo `focus`. In questo caso, l'"handle" del ref non è il nodo DOM, ma l'oggetto personalizzato che crei all'interno della chiamata [`useImperativeHandle`](/reference/react/useImperativeHandle). -## When React attaches the refs {/*when-react-attaches-the-refs*/} +## Quando React collega i refs {/*when-react-attaches-the-refs*/} -In React, every update is split in [two phases](/learn/render-and-commit#step-3-react-commits-changes-to-the-dom): +In React, ogni aggiornamento è diviso in [due fasi](/learn/render-and-commit#step-3-react-commits-changes-to-the-dom): -* During **render,** React calls your components to figure out what should be on the screen. -* During **commit,** React applies changes to the DOM. +* Durante il **rendering,** React chiama i tuoi componenti per capire cosa dovrebbe essere sullo schermo. +* Durante il **commit,** React applica i cambiamenti al DOM. -In general, you [don't want](/learn/referencing-values-with-refs#best-practices-for-refs) to access refs during rendering. That goes for refs holding DOM nodes as well. During the first render, the DOM nodes have not yet been created, so `ref.current` will be `null`. And during the rendering of updates, the DOM nodes haven't been updated yet. So it's too early to read them. +In generale, [non vuoi](/learn/referencing-values-with-refs#best-practices-for-refs) accedere ai refs durante il rendering. Questo vale anche per i refs che contengono nodi DOM. Durante il primo rendering, i nodi DOM non sono ancora stati creati, quindi `ref.current` sarà `null`. E durante il rendering degli aggiornamenti, i nodi DOM non sono ancora stati aggiornati. Quindi è troppo presto per leggerli. -React sets `ref.current` during the commit. Before updating the DOM, React sets the affected `ref.current` values to `null`. After updating the DOM, React immediately sets them to the corresponding DOM nodes. +React imposta `ref.current` durante il commit. Prima di aggiornare il DOM, React imposta i valori `ref.current` interessati a `null`. Dopo aver aggiornato il DOM, React li imposta immediatamente ai nodi DOM corrispondenti. -**Usually, you will access refs from event handlers.** If you want to do something with a ref, but there is no particular event to do it in, you might need an Effect. We will discuss Effects on the next pages. +**Di solito, accederai ai refs dai gestori di eventi.** Se vuoi fare qualcosa con un ref, ma non c'è un evento particolare per farlo, potresti aver bisogno di un Effect. Discuteremo degli Effects nelle prossime pagine. -#### Flushing state updates synchronously with flushSync {/*flushing-state-updates-synchronously-with-flush-sync*/} +#### Svuotare gli aggiornamenti di stato in modo sincrono con flushSync {/*flushing-state-updates-synchronously-with-flush-sync*/} -Consider code like this, which adds a new todo and scrolls the screen down to the last child of the list. Notice how, for some reason, it always scrolls to the todo that was *just before* the last added one: +Considera un codice come questo, che aggiunge un nuovo todo e scorre la schermata fino all'ultimo figlio della lista. Nota come, per qualche motivo, scorre sempre al todo che era *appena prima* dell'ultimo aggiunto: @@ -494,7 +494,7 @@ export default function TodoList() { return ( <> -The issue is with these two lines: +Il problema è con queste due righe: ```js setTodos([ ...todos, newTodo]); listRef.current.lastChild.scrollIntoView(); ``` -In React, [state updates are queued.](/learn/queueing-a-series-of-state-updates) Usually, this is what you want. However, here it causes a problem because `setTodos` does not immediately update the DOM. So the time you scroll the list to its last element, the todo has not yet been added. This is why scrolling always "lags behind" by one item. +In React, [gli aggiornamenti di stato sono messi in coda.](/learn/queueing-a-series-of-state-updates) Di solito, questo è ciò che vuoi. Tuttavia, qui causa un problema perché `setTodos` non aggiorna immediatamente il DOM. Quindi nel momento in cui scorri la lista al suo ultimo elemento, il todo non è ancora stato aggiunto. Ecco perché lo scorrimento è sempre "indietro" di un elemento. -To fix this issue, you can force React to update ("flush") the DOM synchronously. To do this, import `flushSync` from `react-dom` and **wrap the state update** into a `flushSync` call: +Per risolvere questo problema, puoi forzare React ad aggiornare ("svuotare") il DOM in modo sincrono. Per farlo, importa `flushSync` da `react-dom` e **avvolgi l'aggiornamento di stato** in una chiamata `flushSync`: ```js flushSync(() => { @@ -539,7 +539,7 @@ flushSync(() => { listRef.current.lastChild.scrollIntoView(); ``` -This will instruct React to update the DOM synchronously right after the code wrapped in `flushSync` executes. As a result, the last todo will already be in the DOM by the time you try to scroll to it: +Questo istruirà React ad aggiornare il DOM in modo sincrono subito dopo che il codice avvolto in `flushSync` viene eseguito. Di conseguenza, l'ultimo todo sarà già nel DOM nel momento in cui provi a scorrere fino ad esso: @@ -569,7 +569,7 @@ export default function TodoList() { return ( <> -## Best practices for DOM manipulation with refs {/*best-practices-for-dom-manipulation-with-refs*/} +## Migliori pratiche per la manipolazione del DOM con i refs {/*best-practices-for-dom-manipulation-with-refs*/} -Refs are an escape hatch. You should only use them when you have to "step outside React". Common examples of this include managing focus, scroll position, or calling browser APIs that React does not expose. +I refs sono una via di fuga. Dovresti usarli solo quando devi "uscire da React". Esempi comuni di questo includono la gestione del focus, la posizione di scorrimento o la chiamata ad API del browser che React non espone. -If you stick to non-destructive actions like focusing and scrolling, you shouldn't encounter any problems. However, if you try to **modify** the DOM manually, you can risk conflicting with the changes React is making. +Se ti attieni ad azioni non distruttive come il focus e lo scorrimento, non dovresti incontrare problemi. Tuttavia, se provi a **modificare** il DOM manualmente, puoi rischiare di entrare in conflitto con i cambiamenti che React sta facendo. -To illustrate this problem, this example includes a welcome message and two buttons. The first button toggles its presence using [conditional rendering](/learn/conditional-rendering) and [state](/learn/state-a-components-memory), as you would usually do in React. The second button uses the [`remove()` DOM API](https://developer.mozilla.org/en-US/docs/Web/API/Element/remove) to forcefully remove it from the DOM outside of React's control. +Per illustrare questo problema, questo esempio include un messaggio di benvenuto e due pulsanti. Il primo pulsante attiva la sua presenza usando il [rendering condizionale](/learn/conditional-rendering) e lo [stato](/learn/state-a-components-memory), come faresti normalmente in React. Il secondo pulsante usa l'[API DOM `remove()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/remove) per rimuoverlo forzatamente dal DOM al di fuori del controllo di React. -Try pressing "Toggle with setState" a few times. The message should disappear and appear again. Then press "Remove from the DOM". This will forcefully remove it. Finally, press "Toggle with setState": +Prova a premere "Attiva con setState" alcune volte. Il messaggio dovrebbe scomparire e apparire di nuovo. Poi premi "Rimuovi dal DOM". Questo lo rimuoverà forzatamente. Infine, premi "Attiva con setState": @@ -623,15 +623,15 @@ export default function Counter() { onClick={() => { setShow(!show); }}> - Toggle with setState + Attiva con setState - {show &&

Hello world

} + {show &&

Ciao mondo

}
); } @@ -647,20 +647,20 @@ button { -After you've manually removed the DOM element, trying to use `setState` to show it again will lead to a crash. This is because you've changed the DOM, and React doesn't know how to continue managing it correctly. +Dopo aver rimosso manualmente l'elemento DOM, provare a usare `setState` per mostrarlo di nuovo porterà a un crash. Questo perché hai cambiato il DOM, e React non sa come continuare a gestirlo correttamente. -**Avoid changing DOM nodes managed by React.** Modifying, adding children to, or removing children from elements that are managed by React can lead to inconsistent visual results or crashes like above. +**Evita di cambiare i nodi DOM gestiti da React.** Modificare, aggiungere figli a o rimuovere figli da elementi che sono gestiti da React può portare a risultati visivi inconsistenti o crash come sopra. -However, this doesn't mean that you can't do it at all. It requires caution. **You can safely modify parts of the DOM that React has _no reason_ to update.** For example, if some `
` is always empty in the JSX, React won't have a reason to touch its children list. Therefore, it is safe to manually add or remove elements there. +Tuttavia, questo non significa che non puoi farlo affatto. Richiede cautela. **Puoi modificare in sicurezza parti del DOM che React non ha _alcun motivo_ di aggiornare.** Per esempio, se qualche `
` è sempre vuoto nel JSX, React non avrà un motivo per toccare la sua lista di figli. Pertanto, è sicuro aggiungere o rimuovere elementi manualmente lì. -- Refs are a generic concept, but most often you'll use them to hold DOM elements. -- You instruct React to put a DOM node into `myRef.current` by passing `
`. -- Usually, you will use refs for non-destructive actions like focusing, scrolling, or measuring DOM elements. -- A component doesn't expose its DOM nodes by default. You can opt into exposing a DOM node by using the `ref` prop. -- Avoid changing DOM nodes managed by React. -- If you do modify DOM nodes managed by React, modify parts that React has no reason to update. +- I refs sono un concetto generico, ma più spesso li userai per contenere elementi DOM. +- Istruisci React a mettere un nodo DOM in `myRef.current` passando `
`. +- Di solito, userai i refs per azioni non distruttive come il focus, lo scorrimento o la misurazione degli elementi DOM. +- Un componente non espone i suoi nodi DOM per default. Puoi scegliere di esporre un nodo DOM usando la prop `ref`. +- Evita di cambiare i nodi DOM gestiti da React. +- Se modifichi i nodi DOM gestiti da React, modifica le parti che React non ha motivo di aggiornare. @@ -668,9 +668,9 @@ However, this doesn't mean that you can't do it at all. It requires caution. **Y -#### Play and pause the video {/*play-and-pause-the-video*/} +#### Avviare e mettere in pausa il video {/*play-and-pause-the-video*/} -In this example, the button toggles a state variable to switch between a playing and a paused state. However, in order to actually play or pause the video, toggling state is not enough. You also need to call [`play()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play) and [`pause()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/pause) on the DOM element for the `