Skip to content
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

Translate cloneElement.md to pt-br #909

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
113 changes: 56 additions & 57 deletions src/content/reference/react/cloneElement.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ title: cloneElement

<Pitfall>

Using `cloneElement` is uncommon and can lead to fragile code. [See common alternatives.](#alternatives)
Usar `cloneElement` é incomum e pode levar a um código frágil. [Veja alternativas comuns.](#alternatives)

</Pitfall>

<Intro>

`cloneElement` lets you create a new React element using another element as a starting point.
`cloneElement` permite que você crie um novo elemento React usando outro elemento como ponto de partida.

```js
const clonedElement = cloneElement(element, props, ...children)
Expand All @@ -22,11 +22,11 @@ const clonedElement = cloneElement(element, props, ...children)

---

## Reference {/*reference*/}
## Referência {/*reference*/}

### `cloneElement(element, props, ...children)` {/*cloneelement*/}

Call `cloneElement` to create a React element based on the `element`, but with different `props` and `children`:
Chame `cloneElement` para criar um elemento React baseado no `element`, mas com `props` e `children` diferentes:

```js
import { cloneElement } from 'react';
Expand All @@ -43,42 +43,42 @@ const clonedElement = cloneElement(
console.log(clonedElement); // <Row title="Cabbage" isHighlighted={true}>Goodbye</Row>
```

[See more examples below.](#usage)
[Veja mais exemplos abaixo.](#usage)

#### Parameters {/*parameters*/}
#### Parâmetros {/*parameters*/}

* `element`: The `element` argument must be a valid React element. For example, it could be a JSX node like `<Something />`, the result of calling [`createElement`](/reference/react/createElement), or the result of another `cloneElement` call.
* `element`: O argumento `element` deve ser um elemento React válido. Por exemplo, pode ser um nó JSX como `<Something />`, o resultado da chamada [`createElement`](/reference/react/createElement) ou o resultado de outra chamada a `cloneElement`.

* `props`: The `props` argument must either be an object or `null`. If you pass `null`, the cloned element will retain all of the original `element.props`. Otherwise, for every prop in the `props` object, the returned element will "prefer" the value from `props` over the value from `element.props`. The rest of the props will be filled from the original `element.props`. If you pass `props.key` or `props.ref`, they will replace the original ones.
* `props`: O argumento `props` deve ser um objeto ou `null`. Se você passar `null`, o elemento clonado irá reter todas as propriedades do `element` original. Caso contrário, para cada prop no objeto `props`, o elemento retornado "preferirá" o valor de `props` sobre o valor de `element.props`. As demais props serão preenchidas a partir de `element.props` original. Se você passar `props.key` ou `props.ref`, eles substituirão os originais.

* **optional** `...children`: Zero or more child nodes. They can be any React nodes, including React elements, strings, numbers, [portals](/reference/react-dom/createPortal), empty nodes (`null`, `undefined`, `true`, and `false`), and arrays of React nodes. If you don't pass any `...children` arguments, the original `element.props.children` will be preserved.
* **opcional** `...children`: Zero ou mais nós filhos. Eles podem ser quaisquer nós React, incluindo elementos React, strings, números, [portais](/reference/react-dom/createPortal), nós vazios (`null`, `undefined`, `true` e `false`), e arrays de nós React. Se você não passar nenhum argumento `...children`, as `children` do elemento original `element.props` serão preservadas.

#### Returns {/*returns*/}
#### Retorna {/*returns*/}

`cloneElement` returns a React element object with a few properties:
`cloneElement` retorna um objeto de elemento React com algumas propriedades:

* `type`: Same as `element.type`.
* `props`: The result of shallowly merging `element.props` with the overriding `props` you have passed.
* `ref`: The original `element.ref`, unless it was overridden by `props.ref`.
* `key`: The original `element.key`, unless it was overridden by `props.key`.
* `type`: Igual a `element.type`.
* `props`: O resultado da mesclagem superficial de `element.props` com as `props` que você passou.
* `ref`: A `element.ref` original, a menos que tenha sido substituída por `props.ref`.
* `key`: A `element.key` original, a menos que tenha sido substituída por `props.key`.

Usually, you'll return the element from your component or make it a child of another element. Although you may read the element's properties, it's best to treat every element as opaque after it's created, and only render it.
Geralmente, você retornará o elemento do seu componente ou o tornará um filho de outro elemento. Embora você possa ler as propriedades do elemento, é melhor tratar cada elemento como opaco após sua criação, e apenas renderizá-lo.

#### Caveats {/*caveats*/}
#### Ressalvas {/*caveats*/}

* Cloning an element **does not modify the original element.**
* Clonar um elemento **não modifica o elemento original.**

* You should only **pass children as multiple arguments to `cloneElement` if they are all statically known,** like `cloneElement(element, null, child1, child2, child3)`. If your children are dynamic, pass the entire array as the third argument: `cloneElement(element, null, listItems)`. This ensures that React will [warn you about missing `key`s](/learn/rendering-lists#keeping-list-items-in-order-with-key) for any dynamic lists. For static lists this is not necessary because they never reorder.
* Você deve **passar filhos como múltiplos argumentos para `cloneElement` apenas se todos eles forem estaticamente conhecidos,** como `cloneElement(element, null, child1, child2, child3)`. Se seus filhos forem dinâmicos, passe o array inteiro como o terceiro argumento: `cloneElement(element, null, listItems)`. Isso garante que o React irá [avisá-lo sobre chaves faltando](/learn/rendering-lists#keeping-list-items-in-order-with-key) para qualquer lista dinâmica. Para listas estáticas, isso não é necessário porque elas nunca reordenam.

* `cloneElement` makes it harder to trace the data flow, so **try the [alternatives](#alternatives) instead.**
* `cloneElement` torna mais difícil rastrear o fluxo de dados, então **tente as [alternativas](#alternatives) em vez disso.**

---

## Usage {/*usage*/}
## Uso {/*usage*/}

### Overriding props of an element {/*overriding-props-of-an-element*/}
### Sobrescrevendo props de um elemento {/*overriding-props-of-an-element*/}

To override the props of some <CodeStep step={1}>React element</CodeStep>, pass it to `cloneElement` with the <CodeStep step={2}>props you want to override</CodeStep>:
Para sobrescrever as props de algum <CodeStep step={1}>elemento React</CodeStep>, passe-o para `cloneElement` com as <CodeStep step={2}>props que você deseja sobrescrever</CodeStep>:

```js [[1, 5, "<Row title=\\"Cabbage\\" />"], [2, 6, "{ isHighlighted: true }"], [3, 4, "clonedElement"]]
import { cloneElement } from 'react';
Expand All @@ -90,11 +90,11 @@ const clonedElement = cloneElement(
);
```

Here, the resulting <CodeStep step={3}>cloned element</CodeStep> will be `<Row title="Cabbage" isHighlighted={true} />`.
Aqui, o <CodeStep step={3}>elemento clonado</CodeStep> resultante será `<Row title="Cabbage" isHighlighted={true} />`.

**Let's walk through an example to see when it's useful.**
**Vamos passar por um exemplo para ver quando isso é útil.**

Imagine a `List` component that renders its [`children`](/learn/passing-props-to-a-component#passing-jsx-as-children) as a list of selectable rows with a "Next" button that changes which row is selected. The `List` component needs to render the selected `Row` differently, so it clones every `<Row>` child that it has received, and adds an extra `isHighlighted: true` or `isHighlighted: false` prop:
Imagine um componente `List` que renderiza seus [`children`](/learn/passing-props-to-a-component#passing-jsx-as-children) como uma lista de linhas selecionáveis com um botão "Próximo" que altera qual linha está selecionada. O componente `List` precisa renderizar a linha `Row` selecionada de forma diferente, então ele clona cada filho `<Row>` que recebeu e adiciona uma prop extra `isHighlighted: true` ou `isHighlighted: false`:

```js {6-8}
export default function List({ children }) {
Expand All @@ -108,7 +108,7 @@ export default function List({ children }) {
)}
```

Let's say the original JSX received by `List` looks like this:
Vamos supor que o JSX original recebido por `List` pareça assim:

```js {2-4}
<List>
Expand All @@ -118,7 +118,7 @@ Let's say the original JSX received by `List` looks like this:
</List>
```

By cloning its children, the `List` can pass extra information to every `Row` inside. The result looks like this:
Ao clonar seus filhos, `List` pode passar informações extras para cada `Row` dentro. O resultado parece assim:

```js {4,8,12}
<List>
Expand All @@ -137,7 +137,7 @@ By cloning its children, the `List` can pass extra information to every `Row` in
</List>
```

Notice how pressing "Next" updates the state of the `List`, and highlights a different row:
Observe como pressionar "Próximo" atualiza o estado do `List` e destaca uma linha diferente:

<Sandpack>

Expand Down Expand Up @@ -178,7 +178,7 @@ export default function List({ children }) {
(i + 1) % Children.count(children)
);
}}>
Next
Próximo
</button>
</div>
);
Expand Down Expand Up @@ -232,21 +232,21 @@ button {

</Sandpack>

To summarize, the `List` cloned the `<Row />` elements it received and added an extra prop to them.
Para resumir, o `List` clonou os elementos `<Row />` que recebeu e adicionou uma prop extra a eles.

<Pitfall>

Cloning children makes it hard to tell how the data flows through your app. Try one of the [alternatives.](#alternatives)
Clonar filhos torna difícil saber como os dados fluem através do seu aplicativo. Tente uma das [alternativas.](#alternatives)

</Pitfall>

---

## Alternatives {/*alternatives*/}
## Alternativas {/*alternatives*/}

### Passing data with a render prop {/*passing-data-with-a-render-prop*/}
### Passando dados com uma render prop {/*passing-data-with-a-render-prop*/}

Instead of using `cloneElement`, consider accepting a *render prop* like `renderItem`. Here, `List` receives `renderItem` as a prop. `List` calls `renderItem` for every item and passes `isHighlighted` as an argument:
Em vez de usar `cloneElement`, considere aceitar uma *render prop* como `renderItem`. Aqui, `List` recebe `renderItem` como uma prop. `List` chama `renderItem` para cada item e passa `isHighlighted` como um argumento:

```js {1,7}
export default function List({ items, renderItem }) {
Expand All @@ -259,7 +259,7 @@ export default function List({ items, renderItem }) {
})}
```

The `renderItem` prop is called a "render prop" because it's a prop that specifies how to render something. For example, you can pass a `renderItem` implementation that renders a `<Row>` with the given `isHighlighted` value:
A prop `renderItem` é chamada de "render prop" porque é uma prop que especifica como renderizar algo. Por exemplo, você pode passar uma implementação de `renderItem` que renderiza um `<Row>` com o valor `isHighlighted` dado:

```js {3,7}
<List
Expand All @@ -274,7 +274,7 @@ The `renderItem` prop is called a "render prop" because it's a prop that specifi
/>
```

The end result is the same as with `cloneElement`:
O resultado final é o mesmo que com `cloneElement`:

```js {4,8,12}
<List>
Expand All @@ -293,7 +293,7 @@ The end result is the same as with `cloneElement`:
</List>
```

However, you can clearly trace where the `isHighlighted` value is coming from.
No entanto, você pode rastrear claramente de onde vem o valor `isHighlighted`.

<Sandpack>

Expand Down Expand Up @@ -335,7 +335,7 @@ export default function List({ items, renderItem }) {
(i + 1) % items.length
);
}}>
Next
Próximo
</button>
</div>
);
Expand Down Expand Up @@ -389,22 +389,21 @@ button {

</Sandpack>

This pattern is preferred to `cloneElement` because it is more explicit.
Esse padrão é preferido ao `cloneElement` porque é mais explícito.

---

### Passing data through context {/*passing-data-through-context*/}
### Passando dados através do contexto {/*passing-data-through-context*/}

Another alternative to `cloneElement` is to [pass data through context.](/learn/passing-data-deeply-with-context)
Outra alternativa ao `cloneElement` é [passar dados através do contexto.](/learn/passing-data-deeply-with-context)


For example, you can call [`createContext`](/reference/react/createContext) to define a `HighlightContext`:
Por exemplo, você pode chamar [`createContext`](/reference/react/createContext) para definir um `HighlightContext`:

```js
export const HighlightContext = createContext(false);
```

Your `List` component can wrap every item it renders into a `HighlightContext` provider:
Seu componente `List` pode envolver cada item que renderiza em um provedor `HighlightContext`:

```js {8,10}
export default function List({ items, renderItem }) {
Expand All @@ -421,15 +420,15 @@ export default function List({ items, renderItem }) {
})}
```

With this approach, `Row` does not need to receive an `isHighlighted` prop at all. Instead, it reads the context:
Com essa abordagem, `Row` não precisa receber uma prop `isHighlighted` de forma alguma. Em vez disso, ele lê o contexto:

```js src/Row.js {2}
export default function Row({ title }) {
const isHighlighted = useContext(HighlightContext);
// ...
```

This allows the calling component to not know or worry about passing `isHighlighted` to `<Row>`:
Isso permite que o componente chamador não saiba ou se preocupe em passar `isHighlighted` para `<Row>`:

```js {4}
<List
Expand All @@ -440,7 +439,7 @@ This allows the calling component to not know or worry about passing `isHighligh
/>
```

Instead, `List` and `Row` coordinate the highlighting logic through context.
Em vez disso, `List` e `Row` coordenam a lógica de destaque através do contexto.

<Sandpack>

Expand Down Expand Up @@ -486,7 +485,7 @@ export default function List({ items, renderItem }) {
(i + 1) % items.length
);
}}>
Next
Próximo
</button>
</div>
);
Expand Down Expand Up @@ -550,13 +549,13 @@ button {

</Sandpack>

[Learn more about passing data through context.](/reference/react/useContext#passing-data-deeply-into-the-tree)
[Saiba mais sobre passar dados através do contexto.](/reference/react/useContext#passing-data-deeply-into-the-tree)

---

### Extracting logic into a custom Hook {/*extracting-logic-into-a-custom-hook*/}
### Extraindo lógica em um Hook personalizado {/*extracting-logic-into-a-custom-hook*/}

Another approach you can try is to extract the "non-visual" logic into your own Hook, and use the information returned by your Hook to decide what to render. For example, you could write a `useList` custom Hook like this:
Outra abordagem que você pode tentar é extrair a lógica "não visual" em seu próprio Hook, e usar as informações retornadas pelo seu Hook para decidir o que renderizar. Por exemplo, você poderia escrever um Hook personalizado `useList` assim:

```js
import { useState } from 'react';
Expand All @@ -575,7 +574,7 @@ export default function useList(items) {
}
```

Then you could use it like this:
Então você poderia usá-lo assim:

```js {2,9,13}
export default function App() {
Expand All @@ -591,14 +590,14 @@ export default function App() {
)}
<hr />
<button onClick={onNext}>
Next
Próximo
</button>
</div>
);
}
```

The data flow is explicit, but the state is inside the `useList` custom Hook that you can use from any component:
O fluxo de dados é explícito, mas o estado está dentro do Hook personalizado `useList` que você pode usar de qualquer componente:

<Sandpack>

Expand All @@ -620,7 +619,7 @@ export default function App() {
)}
<hr />
<button onClick={onNext}>
Next
Próximo
</button>
</div>
);
Expand Down Expand Up @@ -691,4 +690,4 @@ button {

</Sandpack>

This approach is particularly useful if you want to reuse this logic between different components.
Essa abordagem é particularmente útil se você deseja reutilizar essa lógica entre diferentes componentes.
Loading