Skip to content
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
138 changes: 69 additions & 69 deletions content/blog/2017-09-08-dom-attributes-in-react-16.md
Original file line number Diff line number Diff line change
@@ -1,38 +1,38 @@
---
title: "DOM Attributes in React 16"
title: "Atributos do DOM no React 16"
author: [gaearon]
---

In the past, React used to ignore unknown DOM attributes. If you wrote JSX with an attribute that React doesn't recognize, React would just skip it. For example, this:
No passado, o React ignorava atributos do DOM desconhecidos. Se você escreveu arquivos JSX com um atributo que o React não reconhece, ele apenas ignoraria. Por exemplo:

```js
// Your code:
<div mycustomattribute="something" />
// Seu código:
<div mycustomattribute="alguma coisa" />
```

would render an empty div to the DOM with React 15:
renderizaria uma div vazia no DOM com React 15:

```js
// React 15 output:
// Renderização no React 15:
<div />
```

In React 16, we are making a change. Now, any unknown attributes will end up in the DOM:
No React 16, estamos fazendo uma mudança. Agora, qualquer atributo desconhecido será colocado no DOM:

```js
// React 16 output:
<div mycustomattribute="something" />
// Renderização no React 16:
<div mycustomattribute="alguma coisa" />
```

## Why Are We Changing This? {#why-are-we-changing-this}
## Por Que Estamos Mudando Isso? {#why-are-we-changing-this}

React has always provided a JavaScript-centric API to the DOM. Since React components often take both custom and DOM-related props, it makes sense for React to use the `camelCase` convention just like the DOM APIs:
O React sempre forneceu uma API central do JavaScript para o DOM. Visto que os componentes do React constantemente usam props customizadas e relacionadas ao DOM, faz sentido para o React usar a convenção `camelCase` como nas APis do DOM.

```js
<div tabIndex={-1} />
```

This has not changed. However, the way we enforced it in the past forced us to maintain a whitelist of all valid React DOM attributes in the bundle:
Isso não mudou. Porém, a maneira como aplicamos isso no passado, nos forçou manter uma lista de permissões de todos os atributos do DOM válidos para o React no bundle.

```js
// ...
Expand All @@ -43,145 +43,145 @@ title: 'title',
// ...
```

This had two downsides:
Isso tem duas desvantagens:

* You could not [pass a custom attribute](https://github.com/facebook/react/issues/140). This is useful for supplying browser-specific non-standard attributes, trying new DOM APIs, and integrating with opinionated third-party libraries.
* Você não pode [passar um atributo personalizado](https://github.com/facebook/react/issues/140). Isso é útil por fornecer atributos não padronizados específicos de um navegador, tentando novas APIs do DOM, e interagindo com arbitrárias bibliotecas de terceiros.

* The attribute list kept growing over time, but most React canonical attribute names are already valid in the DOM. Removing most of the whitelist helped us reduce the bundle size a little bit.
* A lista de atributos continuou crescendo ao longo do tempo, porém, a maioria dos atributos canônicos do React já são válidos no DOM. Removendo a maioria das listas de permissões, tornou-se possível reduzir bastante o tamanho do bundle.

With the new approach, both of these problems are solved. With React 16, you can now pass custom attributes to all HTML and SVG elements, and React doesn't have to include the whole attribute whitelist in the production version.
Com uma nova abordagem, ambos problemas foram solucionados. No React 16, você pode passar um atributo personalizado para qualquer elemento HTML e SVG, que o React não irá incluir toda lista de permissões do atributo na versão de produção.

**Note that you should still use the canonical React naming for known attributes:**
**Observe que você ainda deve usar atributos canônicos do React para atributos desconhecidos:**

```js
// Yes, please
<div tabIndex={-1} />
// Sim, por favor
<div tabIndex="-1" />

// Warning: Invalid DOM property `tabindex`. Did you mean `tabIndex`?
<div tabindex={-1} />
// Atenção: Propriedade do DOM `tabindex` inválida. Você quis dizer `tabIndex`?
<div tabindex="-1" />
```

In other words, the way you use DOM components in React hasn't changed, but now you have some new capabilities.
Em outras palavras, a maneira como se usa componentes do DOM no React não mudou, mas agora você tem novos recursos.

## Should I Keep Data in Custom Attributes? {#should-i-keep-data-in-custom-attributes}
## Devo Manter Dados Em Atributos Personalizados? {#should-i-keep-data-in-custom-attributes}

No. We don't encourage you to keep data in DOM attributes. Even if you have to, `data-` attributes are probably a better approach, but in most cases data should be kept in React component state or external stores.
Não. Nós não recomendamos você manter dados em atributos do DOM. Mesmo se você tiver que fazer isso, usar atributos `data-` provavelmente é uma escolha melhor, porém na maioria dos casos deve ser mantido em um estado de um componente React, ou em armazenamentos externos.

However, the new feature is handy if you need to use a non-standard or a new DOM attribute, or if you need to integrate with a third-party library that relies on such attributes.
Entretanto, a nova funcionalidade é de fácil manuseio se você precisa usar um atributo não padronizado, ou um novo atributo do DOM, ou até mesmo se você precisa integrar com bibliotecas terceiras que dependa de tais atributos.

## Data and ARIA Attributes {#data-and-aria-attributes}
## Atributos de Dados e ARIA {#data-and-aria-attributes}

Just like before, React lets you pass `data-` and `aria-` attributes freely:
Assim como antes, o React deixa você passar atributos `data-` e `aria-` livremente:

```js
<div data-foo="42" />
<button aria-label="Close" onClick={onClose} />
```

This has not changed.
Isso não mudou.

[Accessibility](/docs/accessibility.html) is very important, so even though React 16 passes any attributes through, it still validates that `aria-` props have correct names in development mode, just like React 15 did.
[Acessibilidade](/docs/accessibility.html) é muito importante, por isso que o React 16 passa qualquer atributo e também valida se `aria-` props tem seus nomes corretos no modo de desenvolvimento, como o React 15 fazia.

## Migration Path {#migration-path}
## Caminho de Migração {#migration-path}

We have included [a warning about unknown attributes](/warnings/unknown-prop.html) since [React 15.2.0](https://github.com/facebook/react/releases/tag/v15.2.0) which came out more than a year ago. The vast majority of third-party libraries have already updated their code. If your app doesn't produce warnings with React 15.2.0 or higher, this change should not require modifications in your application code.
Nós incluimos uma [notificação sobre atributos desconhecidos](/warnings/unknown-prop.html) desde o [React 15.2.0](https://github.com/facebook/react/releases/tag/v15.2.0) que saiu há mais de um ano. A grande maioria das bibliotecas terceiras já atualizaram seu código. Se sua aplicação ainda não apresenta notificações com o React 15.2.0 ou em suas versões superiores, essa mudança não exigirá modificações no código da sua aplicação.

If you still accidentally forward non-DOM props to DOM components, with React 16 you will start seeing those attributes in the DOM, for example:
Se você ainda envia acidentalmente props que não pertencem ao DOM, à componentes do DOM, com o React 16 você começará a ver esses atributos, por exemplo:

```js
<div myData='[Object object]' />
```

This is somewhat safe (the browser will just ignore them) but we recommend to fix these cases when you see them. One potential hazard is if you pass an object that implements a custom `toString()` or `valueOf()` method that throws. Another possible issue is that legacy HTML attributes like `align` and `valign` will now be passed to the DOM. They used to be stripped out because React didn't support them.
Isso é um pouco seguro (o navegador vai somente ignora-lo), porém nos recomendamos corrigir esses casos assim que eles forem encontrados. Um potencial risco é se você passar um objeto que implementa um método `toString()` ou `valueOf()` personalizado. Outra possível discussão é que os atributos legados de HTML como `align` e `valign` vão ser passados agora pelo DOM. Eles costumavam ser retirados pois o React não os suportava.

To avoid these problems, we suggest to fix the warnings you see in React 15 before upgrading to React 16.
Para evitar esses problemas, nós sugerimos corrigir os avisos no React 15 antes de atualizar para o React 16.

## Changes in Detail {#changes-in-detail}
## Mudanças nos Detalhes {#changes-in-detail}

We've made a few other changes to make the behavior more predictable and help ensure you're not making mistakes. We don't anticipate that these changes are likely to break real-world applications.
Nós fizemos algumas outras mudanças para tornar o comportamento mais previsível e garantir que você não esteja cometendo erros. Nós não esperamos que essas mudanças possam quebrar aplicações existentes.

**These changes only affect DOM components like `<div>`, not your own components.**
**Essas mudanças somente afetam componentes do DOM como `<div>`, mas não seus próprios componentes.**

Below is a detailed list of them.
Abaixo está uma lista detalhada delas.

* **Unknown attributes with string, number, and object values:**
* **Atributos desconhecidos com string, números, e objetos:**

```js
<div mycustomattribute="value" />
<div mycustomattribute={42} />
<div mycustomattribute={myObject} />
```

React 15: Warns and ignores them.
React 16: Converts values to strings and passes them through.
React 15: Avisa e ignora eles.
React 16: Converte os valores para string e passa os valores dos atributos.

*Note: attributes starting with `on` are not passed through as an exception because this could become a potential security hole.*
*Nota: Atributos que começam com `on` não tem seus valores passados como exceção pois pode se tornar uma potencial falha de segurança.*

* **Known attributes with a different canonical React name:**
* **Atributos React conhecidos com um nome canônico diferente:**

```js
<div tabindex={-1} />
<div class="hi" />
```

React 15: Warns and ignores them.
React 16: Warns but converts values to strings and passes them through.
React 15: Avisa e ignora eles.
React 16: Avisa mas converte os valores para strings e passa os valores.

*Note: always use the canonical React naming for all supported attributes.*
*Nota: Sempre use a nomenclatura canônica React para todos os atributos suportados.*

* **Non-boolean attributes with boolean values:**
* **Atributos não boleanos com valores boleanos:**

```js
<div className={false} />
```

React 15: Converts booleans to strings and passes them through.
React 16: Warns and ignores them.
React 15: Converte boleano para string e passa os valores.
React 16: Avisa e ignora eles.

* **Non-event attributes with function values:**
* **Atributos não relacionados a eventos com valores funções:**

```js
<div className={function() {}} />
```

React 15: Converts functions to strings and passes them through.
React 16: Warns and ignores them.
React 15: Converte funções para strings e passa os valores.
React 16: Avisa e ignora eles.

* **Attributes with Symbol values:**
* **Atributos com valores de símbolo:**

```js
<div className={Symbol('foo')} />
```

React 15: Crashes.
React 16: Warns and ignores them.
React 15: Erro.
React 16: Avisa e ignora eles.

* **Attributes with `NaN` values:**
* **Atributos com valores `NaN`:**

```js
<div tabIndex={0 / 0} />
```

React 15: Converts `NaN`s to strings and passes them through.
React 16: Converts `NaN`s to strings and passes them through with a warning.
React 15: Converte `NaN`s para strings e passa os valores.
React 16: Converte `NaN`s para strings e passa os valores com um aviso.

While testing this release, we have also [created an automatically generated table](https://github.com/facebook/react/blob/master/fixtures/attribute-behavior/AttributeTableSnapshot.md) for all known attributes to track potential regressions.
Ao testar esta versão, nós também criamos uma [tabela para todos os atributos conhecidos](https://github.com/facebook/react/blob/master/fixtures/attribute-behavior/AttributeTableSnapshot.md), que atualiza automaticamente, para rastrear possíveis regressões.

## Try It! {#try-it}
## Tente! {#try-it}

You can try the change in [this CodePen](https://codepen.io/gaearon/pen/gxNVdP?editors=0010).
It uses React 16 RC, and you can [help us by testing the RC in your project!](https://github.com/facebook/react/issues/10294)
Você pode tentar essa mudança neste [CodePen](https://codepen.io/gaearon/pen/gxNVdP?editors=0010).
Ele usa React 16 RC, e você pode [nos ajudar testando o RC em seu projeto!](https://github.com/facebook/react/issues/10294)

## Thanks {#thanks}
## Agradecimentos {#thanks}

This effort was largely driven by [Nathan Hunzaker](https://github.com/nhunzaker) who has been a [prolific outside contributor to React](https://github.com/facebook/react/pulls?q=is:pr+author:nhunzaker+is:closed).
Esse esforço foi em grande parte conduzido por [Nathan Hunzaker](https://github.com/nhunzaker) que tem sido um [ativo colaborador externo do React](https://github.com/facebook/react/pulls?q=is:pr+author:nhunzaker+is:closed).

You can find his work on this issue in several PRs over the course of last year: [#6459](https://github.com/facebook/react/pull/6459), [#7311](https://github.com/facebook/react/pull/7311), [#10229](https://github.com/facebook/react/pull/10229), [#10397](https://github.com/facebook/react/pull/10397), [#10385](https://github.com/facebook/react/pull/10385), and [#10470](https://github.com/facebook/react/pull/10470).
Você pode encontrar seu trabalho sobre este assunto em vários PRs ao longo do ano passado: [#6459](https://github.com/facebook/react/pull/6459), [#7311](https://github.com/facebook/react/pull/7311), [#10229](https://github.com/facebook/react/pull/10229), [#10397](https://github.com/facebook/react/pull/10397), [#10385](https://github.com/facebook/react/pull/10385), e [#10470](https://github.com/facebook/react/pull/10470).

Major changes in a popular project can take a lot of time and research. Nathan demonstrated perseverance and commitment to getting this change through, and we are very thankful to him for this and other efforts.
Mudanças importantes em um projeto popular podem exigir muito tempo e pesquisa. Nathan demonstrou perseverança e compromisso em realizar essa mudança, e somos muito gratos a ele por esse e outros esforços.

We would also like to thank [Brandon Dail](https://github.com/aweary) and [Jason Quense](https://github.com/jquense) for their invaluable help maintaining React this year.
Também gostaríamos de agradecer a [Brandon Dail](https://github.com/aweary) e [Jason Quense](https://github.com/jquense) por sua ajuda inestimável para manter o React este ano.

## Future Work {#future-work}
## Trabalho Futuro {#future-work}

We are not changing how [custom elements](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Custom_Elements) work in React 16, but there are [existing discussions](https://github.com/facebook/react/issues/7249) about setting properties instead of attributes, and we might revisit this in React 17. Feel free to chime in if you'd like to help!
Não estamos mudando como [elementos customizados](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Custom_Elements) funcionam no React 16, mas há [discussões existentes](https://github.com/facebook/react/issues/7249) sobre a definição de propriedades em vez de atributos e podemos revisitar isso no React 17. Sinta-se à vontade para entrar em contato se quiser ajudar!