diff --git a/src/content/reference/react-dom/createPortal.md b/src/content/reference/react-dom/createPortal.md index e806660e8..38a5208ab 100644 --- a/src/content/reference/react-dom/createPortal.md +++ b/src/content/reference/react-dom/createPortal.md @@ -1,10 +1,17 @@ --- title: createPortal +translationStatus: ai-draft --- + + +Questa pagina è stata tradotta automaticamente e supervisionata da un maintainer. Un'ulteriore revisione da parte della community sarebbe comunque utile. [Migliora questa traduzione](https://github.com/reactjs/it.react.dev/edit/main/src/content/reference/react-dom/createPortal.md). + + + -`createPortal` lets you render some children into a different part of the DOM. +`createPortal` ti permette di renderizzare alcuni figli in una parte diversa del DOM. ```js @@ -24,7 +31,7 @@ title: createPortal ### `createPortal(children, domNode, key?)` {/*createportal*/} -To create a portal, call `createPortal`, passing some JSX, and the DOM node where it should be rendered: +Per creare un portal, chiama `createPortal` passando del JSX e il nodo DOM in cui deve essere renderizzato: ```js import { createPortal } from 'react-dom'; @@ -32,53 +39,53 @@ import { createPortal } from 'react-dom'; // ...
-

This child is placed in the parent div.

+

Questo figlio è posizionato nel div genitore.

{createPortal( -

This child is placed in the document body.

, +

Questo figlio è posizionato nel body del documento.

, document.body )}
``` -[See more examples below.](#usage) +[Vedi altri esempi sotto.](#usage) -A portal only changes the physical placement of the DOM node. In every other way, the JSX you render into a portal acts as a child node of the React component that renders it. For example, the child can access the context provided by the parent tree, and events bubble up from children to parents according to the React tree. +Un portal modifica solo il posizionamento fisico del nodo DOM. Per il resto, il JSX che renderizzi in un portal si comporta come un nodo figlio del componente React che lo renderizza. Ad esempio, il figlio può accedere al context fornito dall'albero genitore e gli eventi risalgono dai figli ai genitori secondo l'albero React. #### Parameters {/*parameters*/} -* `children`: Anything that can be rendered with React, such as a piece of JSX (e.g. `
` or ``), a [Fragment](/reference/react/Fragment) (`<>...`), a string or a number, or an array of these. +* `children`: Qualsiasi cosa che possa essere renderizzata con React, come un pezzo di JSX (ad es. `
` o ``), un [Fragment](/reference/react/Fragment) (`<>...`), una stringa o un numero, oppure un array di questi. -* `domNode`: Some DOM node, such as those returned by `document.getElementById()`. The node must already exist. Passing a different DOM node during an update will cause the portal content to be recreated. +* `domNode`: Un nodo DOM, come quelli restituiti da `document.getElementById()`. Il nodo deve già esistere. Passare un nodo DOM diverso durante un aggiornamento farà ricreare il contenuto del portal. -* **optional** `key`: A unique string or number to be used as the portal's [key.](/learn/rendering-lists#keeping-list-items-in-order-with-key) +* **optional** `key`: Una stringa o un numero univoco da usare come [key](/learn/rendering-lists#keeping-list-items-in-order-with-key) del portal. #### Returns {/*returns*/} -`createPortal` returns a React node that can be included into JSX or returned from a React component. If React encounters it in the render output, it will place the provided `children` inside the provided `domNode`. +`createPortal` restituisce un nodo React che può essere incluso nel JSX o restituito da un componente React. Se React lo incontra nell'output di renderizzazione, posizionerà i `children` forniti all'interno del `domNode` fornito. #### Caveats {/*caveats*/} -* Events from portals propagate according to the React tree rather than the DOM tree. For example, if you click inside a portal, and the portal is wrapped in `
`, that `onClick` handler will fire. If this causes issues, either stop the event propagation from inside the portal, or move the portal itself up in the React tree. +* Gli eventi dai portal si propagano secondo l'albero React anziché l'albero DOM. Ad esempio, se fai clic all'interno di un portal e il portal è avvolto in `
`, verrà eseguito quel gestore di eventi `onClick`. Se questo causa problemi, interrompi la propagazione dell'evento dall'interno del portal oppure sposta il portal stesso più in alto nell'albero React. --- ## Usage {/*usage*/} -### Rendering to a different part of the DOM {/*rendering-to-a-different-part-of-the-dom*/} +### Renderizzare in una parte diversa del DOM {/*rendering-to-a-different-part-of-the-dom*/} -*Portals* let your components render some of their children into a different place in the DOM. This lets a part of your component "escape" from whatever containers it may be in. For example, a component can display a modal dialog or a tooltip that appears above and outside of the rest of the page. +I *portal* permettono ai tuoi componenti di renderizzare alcuni dei loro figli in un punto diverso del DOM. Così una parte del componente può "uscire" da qualunque contenitore in cui si trovi. Ad esempio, un componente può mostrare una finestra modale o un tooltip che appare sopra e fuori dal resto della pagina. -To create a portal, render the result of `createPortal` with some JSX and the DOM node where it should go: +Per creare un portal, renderizza il risultato di `createPortal` con del JSX e il nodo DOM in cui deve andare: -```js [[1, 8, "

This child is placed in the document body.

"], [2, 9, "document.body"]] +```js [[1, 8, "

Questo figlio è posizionato nel body del documento.

"], [2, 9, "document.body"]] import { createPortal } from 'react-dom'; function MyComponent() { return (
-

This child is placed in the parent div.

+

Questo figlio è posizionato nel div genitore.

{createPortal( -

This child is placed in the document body.

, +

Questo figlio è posizionato nel body del documento.

, document.body )}
@@ -86,9 +93,9 @@ function MyComponent() { } ``` -React will put the DOM nodes for the JSX you passed inside of the DOM node you provided. +React inserirà i nodi DOM del JSX che hai passato all'interno del nodo DOM che hai fornito. -Without a portal, the second `

` would be placed inside the parent `

`, but the portal "teleported" it into the [`document.body`:](https://developer.mozilla.org/en-US/docs/Web/API/Document/body) +Senza un portal, il secondo `

` sarebbe posizionato all'interno del `

` genitore, ma il portal lo ha "teletrasportato" nel [`document.body`:](https://developer.mozilla.org/it/docs/Web/API/Document/body) @@ -98,9 +105,9 @@ import { createPortal } from 'react-dom'; export default function MyComponent() { return (
-

This child is placed in the parent div.

+

Questo figlio è posizionato nel div genitore.

{createPortal( -

This child is placed in the document body.

, +

Questo figlio è posizionato nel body del documento.

, document.body )}
@@ -110,30 +117,30 @@ export default function MyComponent() {
-Notice how the second paragraph visually appears outside the parent `
` with the border. If you inspect the DOM structure with developer tools, you'll see that the second `

` got placed directly into the ``: +Nota come il secondo paragrafo appare visivamente fuori dal `

` genitore con il bordo. Se ispezioni la struttura DOM con gli strumenti per sviluppatori, vedrai che il secondo `

` è stato posizionato direttamente nel ``: ```html {4-6,9}

...
-

This child is placed inside the parent div.

+

Questo figlio è posizionato nel div genitore.

...
-

This child is placed in the document body.

+

Questo figlio è posizionato nel body del documento.

``` -A portal only changes the physical placement of the DOM node. In every other way, the JSX you render into a portal acts as a child node of the React component that renders it. For example, the child can access the context provided by the parent tree, and events still bubble up from children to parents according to the React tree. +Un portal modifica solo il posizionamento fisico del nodo DOM. Per il resto, il JSX che renderizzi in un portal si comporta come un nodo figlio del componente React che lo renderizza. Ad esempio, il figlio può accedere al context fornito dall'albero genitore e gli eventi risalgono comunque dai figli ai genitori secondo l'albero React. --- -### Rendering a modal dialog with a portal {/*rendering-a-modal-dialog-with-a-portal*/} +### Renderizzare una finestra modale con un portal {/*rendering-a-modal-dialog-with-a-portal*/} -You can use a portal to create a modal dialog that floats above the rest of the page, even if the component that summons the dialog is inside a container with `overflow: hidden` or other styles that interfere with the dialog. +Puoi usare un portal per creare una finestra modale che fluttua sopra il resto della pagina, anche se il componente che la invoca si trova dentro un contenitore con `overflow: hidden` o altri stili che interferiscono con la finestra. -In this example, the two containers have styles that disrupt the modal dialog, but the one rendered into a portal is unaffected because, in the DOM, the modal is not contained within the parent JSX elements. +In questo esempio, i due contenitori hanno stili che disturbano la finestra modale, ma quella renderizzata in un portal non ne è influenzata perché, nel DOM, la modale non è contenuta negli elementi JSX genitori. @@ -164,7 +171,7 @@ export default function NoPortalExample() { return ( <> {showModal && ( setShowModal(false)} /> @@ -184,7 +191,7 @@ export default function PortalExample() { return ( <> {showModal && createPortal( setShowModal(false)} />, @@ -199,8 +206,8 @@ export default function PortalExample() { export default function ModalContent({ onClose }) { return (
-
I'm a modal dialog
- +
Sono una finestra modale
+
); } @@ -238,29 +245,29 @@ export default function ModalContent({ onClose }) { -It's important to make sure that your app is accessible when using portals. For instance, you may need to manage keyboard focus so that the user can move the focus in and out of the portal in a natural way. +È importante assicurarsi che l'app sia accessibile quando usi i portal. Ad esempio, potresti dover gestire il focus da tastiera in modo che l'utente possa spostarlo dentro e fuori dal portal in modo naturale. -Follow the [WAI-ARIA Modal Authoring Practices](https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal) when creating modals. If you use a community package, ensure that it is accessible and follows these guidelines. +Segui le [WAI-ARIA Modal Authoring Practices](https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal) quando crei modali. Se usi un pacchetto della community, assicurati che sia accessibile e segua queste linee guida. --- -### Rendering React components into non-React server markup {/*rendering-react-components-into-non-react-server-markup*/} +### Renderizzare componenti React in markup server non React {/*rendering-react-components-into-non-react-server-markup*/} -Portals can be useful if your React root is only part of a static or server-rendered page that isn't built with React. For example, if your page is built with a server framework like Rails, you can create areas of interactivity within static areas such as sidebars. Compared with having [multiple separate React roots,](/reference/react-dom/client/createRoot#rendering-a-page-partially-built-with-react) portals let you treat the app as a single React tree with shared state even though its parts render to different parts of the DOM. +I portal possono essere utili se la root React è solo una parte di una pagina statica o renderizzata lato server che non è costruita con React. Ad esempio, se la pagina è costruita con un framework server come Rails, puoi creare aree di interattività all'interno di aree statiche come le sidebar. Rispetto ad avere [più root React separate,](/reference/react-dom/client/createRoot#rendering-a-page-partially-built-with-react) i portal ti permettono di trattare l'app come un unico albero React con state condiviso anche se le sue parti renderizzano in punti diversi del DOM. ```html public/index.html - My app + La mia app -

Welcome to my hybrid app

+

Benvenuto nella mia app ibrida

@@ -301,11 +308,11 @@ export default function App() { } function MainContent() { - return

This part is rendered by React

; + return

Questa parte è renderizzata da React

; } function SidebarContent() { - return

This part is also rendered by React!

; + return

Anche questa parte è renderizzata da React!

; } ``` @@ -342,15 +349,15 @@ p { --- -### Rendering React components into non-React DOM nodes {/*rendering-react-components-into-non-react-dom-nodes*/} +### Renderizzare componenti React in nodi DOM non React {/*rendering-react-components-into-non-react-dom-nodes*/} -You can also use a portal to manage the content of a DOM node that's managed outside of React. For example, suppose you're integrating with a non-React map widget and you want to render React content inside a popup. To do this, declare a `popupContainer` state variable to store the DOM node you're going to render into: +Puoi anche usare un portal per gestire il contenuto di un nodo DOM gestito al di fuori di React. Ad esempio, supponiamo che tu stia integrando un widget mappa non React e voglia renderizzare contenuto React all'interno di un popup. Per farlo, dichiara una variabile di state `popupContainer` per memorizzare il nodo DOM in cui renderizzerai: ```js const [popupContainer, setPopupContainer] = useState(null); ``` -When you create the third-party widget, store the DOM node returned by the widget so you can render into it: +Quando crei il widget di terze parti, memorizza il nodo DOM restituito dal widget così puoi renderizzare al suo interno: ```js {5-6} useEffect(() => { @@ -363,20 +370,20 @@ useEffect(() => { }, []); ``` -This lets you use `createPortal` to render React content into `popupContainer` once it becomes available: +Questo ti permette di usare `createPortal` per renderizzare contenuto React in `popupContainer` non appena diventa disponibile: ```js {3-6} return (
{popupContainer !== null && createPortal( -

Hello from React!

, +

Ciao da React!

, popupContainer )}
); ``` -Here is a complete example you can play with: +Ecco un esempio completo con cui puoi sperimentare: @@ -420,7 +427,7 @@ export default function Map() { return (
{popupContainer !== null && createPortal( -

Hello from React!

, +

Ciao da React!

, popupContainer )}
diff --git a/src/content/reference/react-dom/flushSync.md b/src/content/reference/react-dom/flushSync.md index 6fe53337d..2d0642579 100644 --- a/src/content/reference/react-dom/flushSync.md +++ b/src/content/reference/react-dom/flushSync.md @@ -1,16 +1,23 @@ --- title: flushSync +translationStatus: ai-draft --- + + +Questa pagina è stata tradotta automaticamente e supervisionata da un maintainer. Un'ulteriore revisione da parte della community sarebbe comunque utile. [Migliora questa traduzione](https://github.com/reactjs/it.react.dev/edit/main/src/content/reference/react-dom/flushSync.md). + + + -Using `flushSync` is uncommon and can hurt the performance of your app. +Usare `flushSync` è poco comune e può compromettere le prestazioni della tua app. -`flushSync` lets you force React to flush any updates inside the provided callback synchronously. This ensures that the DOM is updated immediately. +`flushSync` ti permette di forzare React a svuotare in modo sincrono tutti gli aggiornamenti all'interno della callback fornita. In questo modo il DOM viene aggiornato immediatamente. ```js flushSync(callback) @@ -26,7 +33,7 @@ flushSync(callback) ### `flushSync(callback)` {/*flushsync*/} -Call `flushSync` to force React to flush any pending work and update the DOM synchronously. +Chiama `flushSync` per forzare React a svuotare qualsiasi lavoro in sospeso e ad aggiornare il DOM in modo sincrono. ```js import { flushSync } from 'react-dom'; @@ -36,50 +43,50 @@ flushSync(() => { }); ``` -Most of the time, `flushSync` can be avoided. Use `flushSync` as last resort. +Nella maggior parte dei casi, `flushSync` può essere evitato. Usa `flushSync` come ultima risorsa. -[See more examples below.](#usage) +[Vedi altri esempi sotto.](#usage) #### Parameters {/*parameters*/} -* `callback`: A function. React will immediately call this callback and flush any updates it contains synchronously. It may also flush any pending updates, or Effects, or updates inside of Effects. If an update suspends as a result of this `flushSync` call, the fallbacks may be re-shown. +* `callback`: Una funzione. React chiamerà immediatamente questa callback e svuoterà in modo sincrono tutti gli aggiornamenti che contiene. Può anche svuotare aggiornamenti in sospeso, o Effetti, o aggiornamenti all'interno di Effetti. Se un aggiornamento va in sospensione a causa di questa chiamata a `flushSync`, i fallback potrebbero essere mostrati di nuovo. #### Returns {/*returns*/} -`flushSync` returns `undefined`. +`flushSync` restituisce `undefined`. #### Caveats {/*caveats*/} -* `flushSync` can significantly hurt performance. Use sparingly. -* `flushSync` may force pending Suspense boundaries to show their `fallback` state. -* `flushSync` may run pending Effects and synchronously apply any updates they contain before returning. -* `flushSync` may flush updates outside the callback when necessary to flush the updates inside the callback. For example, if there are pending updates from a click, React may flush those before flushing the updates inside the callback. +* `flushSync` può compromettere significativamente le prestazioni. Usalo con parsimonia. +* `flushSync` può forzare i confini Suspense in sospeso a mostrare il `fallback`. +* `flushSync` può eseguire Effetti in sospeso e applicare in modo sincrono tutti gli aggiornamenti che contengono prima di restituire il controllo. +* `flushSync` può svuotare aggiornamenti al di fuori della callback quando necessario per svuotare gli aggiornamenti all'interno della callback. Ad esempio, se ci sono aggiornamenti in sospeso da un click, React potrebbe svuotarli prima di svuotare gli aggiornamenti all'interno della callback. --- ## Usage {/*usage*/} -### Flushing updates for third-party integrations {/*flushing-updates-for-third-party-integrations*/} +### Svuotare gli aggiornamenti per integrazioni con terze parti {/*flushing-updates-for-third-party-integrations*/} -When integrating with third-party code such as browser APIs or UI libraries, it may be necessary to force React to flush updates. Use `flushSync` to force React to flush any state updates inside the callback synchronously: +Quando integri codice di terze parti come API del browser o librerie UI, potrebbe essere necessario forzare React a svuotare gli aggiornamenti. Usa `flushSync` per forzare React a svuotare in modo sincrono tutti gli aggiornamenti di state all'interno della callback: ```js [[1, 2, "setSomething(123)"]] flushSync(() => { setSomething(123); }); -// By this line, the DOM is updated. +// A questo punto, il DOM è aggiornato. ``` -This ensures that, by the time the next line of code runs, React has already updated the DOM. +In questo modo, quando viene eseguita la riga di codice successiva, React ha già aggiornato il DOM. -**Using `flushSync` is uncommon, and using it often can significantly hurt the performance of your app.** If your app only uses React APIs, and does not integrate with third-party libraries, `flushSync` should be unnecessary. +**Usare `flushSync` è poco comune, e usarlo spesso può compromettere significativamente le prestazioni della tua app.** Se la tua app usa solo API React e non si integra con librerie di terze parti, `flushSync` dovrebbe essere superfluo. -However, it can be helpful for integrating with third-party code like browser APIs. +Tuttavia, può essere utile per integrarsi con codice di terze parti come le API del browser. -Some browser APIs expect results inside of callbacks to be written to the DOM synchronously, by the end of the callback, so the browser can do something with the rendered DOM. In most cases, React handles this for you automatically. But in some cases it may be necessary to force a synchronous update. +Alcune API del browser si aspettano che i risultati all'interno delle callback vengano scritti nel DOM in modo sincrono, entro la fine della callback, così che il browser possa fare qualcosa con il DOM renderizzato. Nella maggior parte dei casi, React gestisce questo automaticamente. Ma in alcuni casi potrebbe essere necessario forzare un aggiornamento sincrono. -For example, the browser `onbeforeprint` API allows you to change the page immediately before the print dialog opens. This is useful for applying custom print styles that allow the document to display better for printing. In the example below, you use `flushSync` inside of the `onbeforeprint` callback to immediately "flush" the React state to the DOM. Then, by the time the print dialog opens, `isPrinting` displays "yes": +Ad esempio, l'API `onbeforeprint` del browser ti permette di modificare la pagina immediatamente prima che si apra la finestra di dialogo di stampa. È utile per applicare stili di stampa personalizzati che permettono al documento di essere visualizzato meglio in stampa. Nell'esempio qui sotto, usi `flushSync` all'interno della callback `onbeforeprint` per "svuotare" immediatamente lo state React nel DOM. Così, quando si apre la finestra di dialogo di stampa, `isPrinting` mostra "yes": @@ -113,7 +120,7 @@ export default function PrintApp() { <>

isPrinting: {isPrinting ? 'yes' : 'no'}

); @@ -122,13 +129,13 @@ export default function PrintApp() {
-Without `flushSync`, the print dialog will display `isPrinting` as "no". This is because React batches the updates asynchronously and the print dialog is displayed before the state is updated. +Senza `flushSync`, la finestra di dialogo di stampa mostrerà `isPrinting` come "no". Questo perché React raggruppa gli aggiornamenti in modo asincrono e la finestra di dialogo di stampa viene visualizzata prima che lo state venga aggiornato. -`flushSync` can significantly hurt performance, and may unexpectedly force pending Suspense boundaries to show their fallback state. +`flushSync` può compromettere significativamente le prestazioni e può forzare in modo imprevisto i confini Suspense in sospeso a mostrare il `fallback`. -Most of the time, `flushSync` can be avoided, so use `flushSync` as a last resort. +Nella maggior parte dei casi, `flushSync` può essere evitato, quindi usalo come ultima risorsa. @@ -136,10 +143,10 @@ Most of the time, `flushSync` can be avoided, so use `flushSync` as a last resor ## Troubleshooting {/*troubleshooting*/} -### I'm getting an error: "flushSync was called from inside a lifecycle method" {/*im-getting-an-error-flushsync-was-called-from-inside-a-lifecycle-method*/} +### Ricevo un errore: "flushSync was called from inside a lifecycle method" {/*im-getting-an-error-flushsync-was-called-from-inside-a-lifecycle-method*/} -React cannot `flushSync` in the middle of a render. If you do, it will noop and warn: +React non può eseguire `flushSync` nel mezzo di una renderizzazione. Se lo fai, non avrà effetto e mostrerà un avviso: @@ -147,13 +154,13 @@ Warning: flushSync was called from inside a lifecycle method. React cannot flush -This includes calling `flushSync` inside: +Questo include la chiamata a `flushSync` all'interno di: -- rendering a component. -- `useLayoutEffect` or `useEffect` hooks. -- Class component lifecycle methods. +- la renderizzazione di un componente. +- gli hooks `useLayoutEffect` o `useEffect`. +- i metodi lifecycle dei componenti classe. -For example, calling `flushSync` in an Effect will noop and warn: +Ad esempio, chiamare `flushSync` in un Effetto non avrà effetto e mostrerà un avviso: ```js import { useEffect } from 'react'; @@ -161,7 +168,7 @@ import { flushSync } from 'react-dom'; function MyComponent() { useEffect(() => { - // 🚩 Wrong: calling flushSync inside an effect + // 🚩 Sbagliato: chiamare flushSync all'interno di un Effetto flushSync(() => { setSomething(newValue); }); @@ -171,11 +178,11 @@ function MyComponent() { } ``` -To fix this, you usually want to move the `flushSync` call to an event: +Per risolvere, di solito vuoi spostare la chiamata a `flushSync` in un evento: ```js function handleClick() { - // ✅ Correct: flushSync in event handlers is safe + // ✅ Corretto: flushSync nei gestori di eventi è sicuro flushSync(() => { setSomething(newValue); }); @@ -183,11 +190,11 @@ function handleClick() { ``` -If it's difficult to move to an event, you can defer `flushSync` in a microtask: +Se è difficile spostarlo in un evento, puoi rimandare `flushSync` in una microtask: ```js {3,7} useEffect(() => { - // ✅ Correct: defer flushSync to a microtask + // ✅ Corretto: rimandare flushSync a una microtask queueMicrotask(() => { flushSync(() => { setSomething(newValue); @@ -196,10 +203,10 @@ useEffect(() => { }, []); ``` -This will allow the current render to finish and schedule another syncronous render to flush the updates. +Questo permetterà alla renderizzazione corrente di completarsi e programmerà un'altra renderizzazione sincrona per svuotare gli aggiornamenti. -`flushSync` can significantly hurt performance, but this particular pattern is even worse for performance. Exhaust all other options before calling `flushSync` in a microtask as an escape hatch. +`flushSync` può compromettere significativamente le prestazioni, ma questo particolare pattern è ancora peggio per le prestazioni. Esaurisci tutte le altre opzioni prima di chiamare `flushSync` in una microtask come escape hatch.