From 1f4c5382b34d8ad6a52e71bde04fd7b2d5054c05 Mon Sep 17 00:00:00 2001 From: manuel Date: Mon, 23 Jun 2025 16:42:44 +0100 Subject: [PATCH 1/2] feat: add Portuguese translation for "Thinking in React" tutorial --- next-env.d.ts | 3 +- src/content/learn/thinking-in-react.md | 171 ++++++++++++------------- 2 files changed, 86 insertions(+), 88 deletions(-) diff --git a/next-env.d.ts b/next-env.d.ts index 3cd7048ed..52e831b43 100644 --- a/next-env.d.ts +++ b/next-env.d.ts @@ -1,6 +1,5 @@ /// /// -/// // NOTE: This file should not be edited -// see https://nextjs.org/docs/app/api-reference/config/typescript for more information. +// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information. diff --git a/src/content/learn/thinking-in-react.md b/src/content/learn/thinking-in-react.md index 822891e60..99d47a6ca 100644 --- a/src/content/learn/thinking-in-react.md +++ b/src/content/learn/thinking-in-react.md @@ -1,18 +1,18 @@ --- -title: Thinking in React +title: Pensando em React --- -React can change how you think about the designs you look at and the apps you build. When you build a user interface with React, you will first break it apart into pieces called *components*. Then, you will describe the different visual states for each of your components. Finally, you will connect your components together so that the data flows through them. In this tutorial, we’ll guide you through the thought process of building a searchable product data table with React. +O React pode mudar a forma como você pensa sobre os designs que observa e as aplicações que constrói. Quando você constrói uma interface de usuário com React, primeiro você a dividirá em partes chamadas *componentes*. Em seguida, você descreverá os diferentes estados visuais para cada um dos seus componentes. Finalmente, você conectará seus componentes para que os dados fluam através deles. Neste tutorial, nós o guiaremos através do processo de pensamento de construir uma tabela de dados de produtos pesquisável com React. -## Start with the mockup {/*start-with-the-mockup*/} +## Comece com o mockup {/*start-with-the-mockup*/} -Imagine that you already have a JSON API and a mockup from a designer. +Imagine que você já tem uma API JSON e um mockup de um designer. -The JSON API returns some data that looks like this: +A API JSON retorna alguns dados que se parecem com isto: ```json [ @@ -25,25 +25,25 @@ The JSON API returns some data that looks like this: ] ``` -The mockup looks like this: +O mockup se parece com isto: -To implement a UI in React, you will usually follow the same five steps. +Para implementar uma UI em React, você geralmente seguirá os mesmos cinco passos. -## Step 1: Break the UI into a component hierarchy {/*step-1-break-the-ui-into-a-component-hierarchy*/} +## Passo 1: Divida a UI em uma hierarquia de componentes {/*step-1-break-the-ui-into-a-component-hierarchy*/} -Start by drawing boxes around every component and subcomponent in the mockup and naming them. If you work with a designer, they may have already named these components in their design tool. Ask them! +Comece desenhando caixas ao redor de cada componente e subcomponente no mockup e nomeando-os. Se você trabalha com um designer, eles podem já ter nomeado esses componentes em sua ferramenta de design. Pergunte a eles! -Depending on your background, you can think about splitting up a design into components in different ways: +Dependendo do seu background, você pode pensar sobre dividir um design em componentes de diferentes maneiras: -* **Programming**--use the same techniques for deciding if you should create a new function or object. One such technique is the [single responsibility principle](https://en.wikipedia.org/wiki/Single_responsibility_principle), that is, a component should ideally only do one thing. If it ends up growing, it should be decomposed into smaller subcomponents. -* **CSS**--consider what you would make class selectors for. (However, components are a bit less granular.) -* **Design**--consider how you would organize the design's layers. +* **Programação**--use as mesmas técnicas para decidir se você deve criar uma nova função ou objeto. Uma dessas técnicas é o [princípio da responsabilidade única](https://en.wikipedia.org/wiki/Single_responsibility_principle), ou seja, um componente deve idealmente fazer apenas uma coisa. Se ele acabar crescendo, deve ser decomposto em subcomponentes menores. +* **CSS**--considere para o que você faria seletores de classe. (No entanto, os componentes são um pouco menos granulares.) +* **Design**--considere como você organizaria as camadas do design. -If your JSON is well-structured, you'll often find that it naturally maps to the component structure of your UI. That's because UI and data models often have the same information architecture--that is, the same shape. Separate your UI into components, where each component matches one piece of your data model. +Se seu JSON está bem estruturado, você frequentemente descobrirá que ele mapeia naturalmente para a estrutura de componentes de sua UI. Isso ocorre porque UI e modelos de dados frequentemente têm a mesma arquitetura de informação--ou seja, a mesma forma. Separe sua UI em componentes, onde cada componente corresponde a uma parte do seu modelo de dados. -There are five components on this screen: +Há cinco componentes nesta tela: @@ -51,19 +51,19 @@ There are five components on this screen: -1. `FilterableProductTable` (grey) contains the entire app. -2. `SearchBar` (blue) receives the user input. -3. `ProductTable` (lavender) displays and filters the list according to the user input. -4. `ProductCategoryRow` (green) displays a heading for each category. -5. `ProductRow` (yellow) displays a row for each product. +1. `FilterableProductTable` (cinza) contém toda a aplicação. +2. `SearchBar` (azul) recebe a entrada do usuário. +3. `ProductTable` (lavanda) exibe e filtra a lista de acordo com a entrada do usuário. +4. `ProductCategoryRow` (verde) exibe um cabeçalho para cada categoria. +5. `ProductRow` (amarelo) exibe uma linha para cada produto. -If you look at `ProductTable` (lavender), you'll see that the table header (containing the "Name" and "Price" labels) isn't its own component. This is a matter of preference, and you could go either way. For this example, it is a part of `ProductTable` because it appears inside the `ProductTable`'s list. However, if this header grows to be complex (e.g., if you add sorting), you can move it into its own `ProductTableHeader` component. +Se você olhar para `ProductTable` (lavanda), verá que o cabeçalho da tabela (contendo os rótulos "Name" e "Price") não é seu próprio componente. Esta é uma questão de preferência, e você pode ir de qualquer forma. Para este exemplo, é parte de `ProductTable` porque aparece dentro da lista de `ProductTable`. No entanto, se este cabeçalho crescer para ser complexo (por exemplo, se você adicionar ordenação), você pode movê-lo para seu próprio componente `ProductTableHeader`. -Now that you've identified the components in the mockup, arrange them into a hierarchy. Components that appear within another component in the mockup should appear as a child in the hierarchy: +Agora que você identificou os componentes no mockup, organize-os em uma hierarquia. Componentes que aparecem dentro de outro componente no mockup devem aparecer como filhos na hierarquia: * `FilterableProductTable` * `SearchBar` @@ -71,13 +71,13 @@ Now that you've identified the components in the mockup, arrange them into a hie * `ProductCategoryRow` * `ProductRow` -## Step 2: Build a static version in React {/*step-2-build-a-static-version-in-react*/} +## Passo 2: Construa uma versão estática em React {/*step-2-build-a-static-version-in-react*/} -Now that you have your component hierarchy, it's time to implement your app. The most straightforward approach is to build a version that renders the UI from your data model without adding any interactivity... yet! It's often easier to build the static version first and add interactivity later. Building a static version requires a lot of typing and no thinking, but adding interactivity requires a lot of thinking and not a lot of typing. +Agora que você tem sua hierarquia de componentes, é hora de implementar sua aplicação. A abordagem mais direta é construir uma versão que renderiza a UI a partir do seu modelo de dados sem adicionar qualquer interatividade... ainda! É frequentemente mais fácil construir a versão estática primeiro e adicionar interatividade depois. Construir uma versão estática requer muito digitação e nenhum pensamento, mas adicionar interatividade requer muito pensamento e pouca digitação. -To build a static version of your app that renders your data model, you'll want to build [components](/learn/your-first-component) that reuse other components and pass data using [props.](/learn/passing-props-to-a-component) Props are a way of passing data from parent to child. (If you're familiar with the concept of [state](/learn/state-a-components-memory), don't use state at all to build this static version. State is reserved only for interactivity, that is, data that changes over time. Since this is a static version of the app, you don't need it.) +Para construir uma versão estática de sua aplicação que renderiza seu modelo de dados, você vai querer construir [componentes](/learn/your-first-component) que reutilizam outros componentes e passam dados usando [props.](/learn/passing-props-to-a-component) Props são uma forma de passar dados de pai para filho. (Se você está familiarizado com o conceito de [state](/learn/state-a-components-memory), não use state de forma alguma para construir esta versão estática. State é reservado apenas para interatividade, ou seja, dados that change over time. Como esta é uma versão estática da aplicação, você não precisa dele.) -You can either build "top down" by starting with building the components higher up in the hierarchy (like `FilterableProductTable`) or "bottom up" by working from components lower down (like `ProductRow`). In simpler examples, it’s usually easier to go top-down, and on larger projects, it’s easier to go bottom-up. +Você pode construir "de cima para baixo" começando com a construção dos componentes mais altos na hierarquia (como `FilterableProductTable`) ou "de baixo para cima" trabalhando a partir de componentes mais baixos (como `ProductRow`). Em exemplos mais simples, é geralmente mais fácil ir de cima para baixo, e em projetos maiores, é mais fácil ir de baixo para cima. @@ -195,85 +195,85 @@ td { -(If this code looks intimidating, go through the [Quick Start](/learn/) first!) +(Se este código parece intimidante, passe pelo [Início Rápido](/learn/) primeiro!) -After building your components, you'll have a library of reusable components that render your data model. Because this is a static app, the components will only return JSX. The component at the top of the hierarchy (`FilterableProductTable`) will take your data model as a prop. This is called _one-way data flow_ because the data flows down from the top-level component to the ones at the bottom of the tree. +Depois de construir seus componentes, você terá uma biblioteca de componentes reutilizáveis que renderizam seu modelo de dados. Como esta é uma aplicação estática, os componentes apenas retornarão JSX. O componente no topo da hierarquia (`FilterableProductTable`) receberá seu modelo de dados como prop. Isso é chamado de _fluxo de dados unidirecional_ porque os dados fluem de cima do componente de nível superior para os da parte inferior da árvore. -At this point, you should not be using any state values. That’s for the next step! +Neste ponto, você não deve estar usando nenhum valor de state. Isso é para o próximo passo! -## Step 3: Find the minimal but complete representation of UI state {/*step-3-find-the-minimal-but-complete-representation-of-ui-state*/} +## Passo 3: Encontre a representação mínima mas completa do estado da UI {/*step-3-find-the-minimal-but-complete-representation-of-ui-state*/} -To make the UI interactive, you need to let users change your underlying data model. You will use *state* for this. +Para tornar a UI interativa, você precisa permitir que os usuários alterem seu modelo de dados subjacente. Você usará *state* para isso. -Think of state as the minimal set of changing data that your app needs to remember. The most important principle for structuring state is to keep it [DRY (Don't Repeat Yourself).](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) Figure out the absolute minimal representation of the state your application needs and compute everything else on-demand. For example, if you're building a shopping list, you can store the items as an array in state. If you want to also display the number of items in the list, don't store the number of items as another state value--instead, read the length of your array. +Pense no state como o conjunto mínimo de dados em mudança que sua aplicação precisa lembrar. O princípio mais importante para estruturar o state é mantê-lo [DRY (Don't Repeat Yourself - Não Se Repita).](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) Descubra a representação absolutamente mínima do state que sua aplicação precisa e compute todo o resto sob demanda. Por exemplo, se você está construindo uma lista de compras, você pode armazenar os itens como um array no state. Se você também quer exibir o número de itens na lista, não armazene o número de itens como outro valor de state--em vez disso, leia o comprimento do seu array. -Now think of all of the pieces of data in this example application: +Agora pense em todas as partes de dados nesta aplicação de exemplo: -1. The original list of products -2. The search text the user has entered -3. The value of the checkbox -4. The filtered list of products +1. A lista original de produtos +2. O texto de busca que o usuário digitou +3. O valor da checkbox +4. A lista filtrada de produtos -Which of these are state? Identify the ones that are not: +Quais desses são state? Identifique os que não são: -* Does it **remain unchanged** over time? If so, it isn't state. -* Is it **passed in from a parent** via props? If so, it isn't state. -* **Can you compute it** based on existing state or props in your component? If so, it *definitely* isn't state! +* **Permanece inalterado** ao longo do tempo? Se sim, não é state. +* É **passado de um pai** via props? Se sim, não é state. +* **Você pode computá-lo** baseado no state ou props existentes em seu componente? Se sim, *definitivamente* não é state! -What's left is probably state. +O que sobra provavelmente é state. -Let's go through them one by one again: +Vamos passá-los um por um novamente: -1. The original list of products is **passed in as props, so it's not state.** -2. The search text seems to be state since it changes over time and can't be computed from anything. -3. The value of the checkbox seems to be state since it changes over time and can't be computed from anything. -4. The filtered list of products **isn't state because it can be computed** by taking the original list of products and filtering it according to the search text and value of the checkbox. +1. A lista original de produtos é **passada como props, então não é state.** +2. O texto de busca parece ser state já que muda ao longo do tempo e não pode ser computado a partir de nada. +3. O valor da checkbox parece ser state já que muda ao longo do tempo e não pode ser computado a partir de nada. +4. A lista filtrada de produtos **não é state porque pode ser computada** pegando a lista original de produtos e filtrando-a de acordo com o texto de busca e o valor da checkbox. -This means only the search text and the value of the checkbox are state! Nicely done! +Isso significa que apenas o texto de busca e o valor da checkbox são state! Muito bem! #### Props vs State {/*props-vs-state*/} -There are two types of "model" data in React: props and state. The two are very different: +Há dois tipos de dados "modelo" em React: props e state. Os dois são muito diferentes: -* [**Props** are like arguments you pass](/learn/passing-props-to-a-component) to a function. They let a parent component pass data to a child component and customize its appearance. For example, a `Form` can pass a `color` prop to a `Button`. -* [**State** is like a component’s memory.](/learn/state-a-components-memory) It lets a component keep track of some information and change it in response to interactions. For example, a `Button` might keep track of `isHovered` state. +* [**Props** são como argumentos que você passa](/learn/passing-props-to-a-component) para uma função. Eles permitem que um componente pai passe dados para um componente filho e personalize sua aparência. Por exemplo, um `Form` pode passar uma prop `color` para um `Button`. +* [**State** é como a memória de um componente.](/learn/state-a-components-memory) Ele permite que um componente mantenha controle de algumas informações e as altere em resposta a interações. Por exemplo, um `Button` pode manter controle do state `isHovered`. -Props and state are different, but they work together. A parent component will often keep some information in state (so that it can change it), and *pass it down* to child components as their props. It's okay if the difference still feels fuzzy on the first read. It takes a bit of practice for it to really stick! +Props e state são diferentes, mas trabalham juntos. Um componente pai frequentemente manterá algumas informações no state (para que possa alterá-las), e *passá-las para baixo* para componentes filhos como suas props. É normal se a diferença ainda parecer confusa na primeira leitura. Leva um pouco de prática para realmente entender! -## Step 4: Identify where your state should live {/*step-4-identify-where-your-state-should-live*/} +## Passo 4: Identifique onde seu state deve viver {/*step-4-identify-where-your-state-should-live*/} -After identifying your app’s minimal state data, you need to identify which component is responsible for changing this state, or *owns* the state. Remember: React uses one-way data flow, passing data down the component hierarchy from parent to child component. It may not be immediately clear which component should own what state. This can be challenging if you’re new to this concept, but you can figure it out by following these steps! +Depois de identificar os dados de state mínimos da sua aplicação, você precisa identificar qual componente é responsável por alterar este state, ou *possui* o state. Lembre-se: o React usa fluxo de dados unidirecional, passando dados pela hierarquia de componentes do componente pai para o componente filho. Pode não estar imediatamente claro qual componente deve possuir qual state. Isso pode ser desafiador se você é novo neste conceito, mas você pode descobrir seguindo estes passos! -For each piece of state in your application: +Para cada parte do state em sua aplicação: -1. Identify *every* component that renders something based on that state. -2. Find their closest common parent component--a component above them all in the hierarchy. -3. Decide where the state should live: - 1. Often, you can put the state directly into their common parent. - 2. You can also put the state into some component above their common parent. - 3. If you can't find a component where it makes sense to own the state, create a new component solely for holding the state and add it somewhere in the hierarchy above the common parent component. +1. Identifique *todos* os componentes que renderizam algo baseado naquele state. +2. Encontre o componente pai comum mais próximo--um componente acima de todos eles na hierarquia. +3. Decida onde o state deve viver: + 1. Frequentemente, você pode colocar o state diretamente no pai comum deles. + 2. Você também pode colocar o state em algum componente acima do pai comum deles. + 3. Se você não conseguir encontrar um componente onde faça sentido possuir o state, crie um novo componente apenas para manter o state e adicione-o em algum lugar na hierarquia acima do componente pai comum. -In the previous step, you found two pieces of state in this application: the search input text, and the value of the checkbox. In this example, they always appear together, so it makes sense to put them into the same place. +No passo anterior, você encontrou duas partes de state nesta aplicação: o texto de entrada de busca, e o valor da checkbox. Neste exemplo, eles sempre aparecem juntos, então faz sentido colocá-los no mesmo lugar. -Now let's run through our strategy for them: +Agora vamos executar nossa estratégia para eles: -1. **Identify components that use state:** - * `ProductTable` needs to filter the product list based on that state (search text and checkbox value). - * `SearchBar` needs to display that state (search text and checkbox value). -2. **Find their common parent:** The first parent component both components share is `FilterableProductTable`. -3. **Decide where the state lives**: We'll keep the filter text and checked state values in `FilterableProductTable`. +1. **Identifique componentes que usam state:** + * `ProductTable` precisa filtrar a lista de produtos baseada naquele state (texto de busca e valor da checkbox). + * `SearchBar` precisa exibir aquele state (texto de busca e valor da checkbox). +2. **Encontre o pai comum:** O primeiro componente pai que ambos os componentes compartilham é `FilterableProductTable`. +3. **Decida onde o state vive**: Vamos manter os valores de texto de filtro e estado marcado em `FilterableProductTable`. -So the state values will live in `FilterableProductTable`. +Então os valores de state viverão em `FilterableProductTable`. -Add state to the component with the [`useState()` Hook.](/reference/react/useState) Hooks are special functions that let you "hook into" React. Add two state variables at the top of `FilterableProductTable` and specify their initial state: +Adicione state ao componente com o [`useState()` Hook.](/reference/react/useState) Hooks são funções especiais que permitem que você "se conecte" ao React. Adicione duas variáveis de state no topo de `FilterableProductTable` e especifique seu state inicial: ```js function FilterableProductTable({ products }) { @@ -281,7 +281,7 @@ function FilterableProductTable({ products }) { const [inStockOnly, setInStockOnly] = useState(false); ``` -Then, pass `filterText` and `inStockOnly` to `ProductTable` and `SearchBar` as props: +Em seguida, passe `filterText` e `inStockOnly` para `ProductTable` e `SearchBar` como props: ```js
@@ -295,7 +295,7 @@ Then, pass `filterText` and `inStockOnly` to `ProductTable` and `SearchBar` as p
``` -You can start seeing how your application will behave. Edit the `filterText` initial value from `useState('')` to `useState('fruit')` in the sandbox code below. You'll see both the search input text and the table update: +Você pode começar a ver como sua aplicação se comportará. Edite o valor inicial de `filterText` de `useState('')` para `useState('fruit')` no código sandbox abaixo. Você verá tanto o texto de entrada de busca quanto a tabela atualizarem: @@ -437,15 +437,15 @@ td { -Notice that editing the form doesn't work yet. There is a console error in the sandbox above explaining why: +Note que editar o formulário ainda não funciona. Há um erro no console no sandbox acima explicando o porquê: -You provided a \`value\` prop to a form field without an \`onChange\` handler. This will render a read-only field. +Você forneceu uma prop \`value\` para um campo de formulário sem um manipulador \`onChange\`. Isso renderizará um campo somente leitura. -In the sandbox above, `ProductTable` and `SearchBar` read the `filterText` and `inStockOnly` props to render the table, the input, and the checkbox. For example, here is how `SearchBar` populates the input value: +No sandbox acima, `ProductTable` e `SearchBar` leem as props `filterText` e `inStockOnly` para renderizar a tabela, a entrada, e a checkbox. Por exemplo, aqui está como `SearchBar` popula o valor da entrada: ```js {1,6} function SearchBar({ filterText, inStockOnly }) { @@ -457,16 +457,15 @@ function SearchBar({ filterText, inStockOnly }) { placeholder="Search..."/> ``` -However, you haven't added any code to respond to the user actions like typing yet. This will be your final step. +No entanto, você ainda não adicionou nenhum código para responder às ações do usuário como digitação. Este será seu passo final. +## Passo 5: Adicione fluxo de dados inverso {/*step-5-add-inverse-data-flow*/} -## Step 5: Add inverse data flow {/*step-5-add-inverse-data-flow*/} +Atualmente sua aplicação renderiza corretamente com props e state fluindo pela hierarquia. Mas para alterar o state de acordo com a entrada do usuário, você precisará suportar dados fluindo no outro sentido: os componentes de formulário profundos na hierarquia precisam atualizar o state em `FilterableProductTable`. -Currently your app renders correctly with props and state flowing down the hierarchy. But to change the state according to user input, you will need to support data flowing the other way: the form components deep in the hierarchy need to update the state in `FilterableProductTable`. +O React torna este fluxo de dados explícito, mas requer um pouco mais de digitação do que vinculação de dados bidirecional. Se você tentar digitar ou marcar a caixa no exemplo acima, verá que o React ignora sua entrada. Isso é intencional. Ao escrever ``, você definiu a prop `value` do `input` para sempre ser igual ao state `filterText` passado de `FilterableProductTable`. Como o state `filterText` nunca é definido, a entrada nunca muda. -React makes this data flow explicit, but it requires a little more typing than two-way data binding. If you try to type or check the box in the example above, you'll see that React ignores your input. This is intentional. By writing ``, you've set the `value` prop of the `input` to always be equal to the `filterText` state passed in from `FilterableProductTable`. Since `filterText` state is never set, the input never changes. - -You want to make it so whenever the user changes the form inputs, the state updates to reflect those changes. The state is owned by `FilterableProductTable`, so only it can call `setFilterText` and `setInStockOnly`. To let `SearchBar` update the `FilterableProductTable`'s state, you need to pass these functions down to `SearchBar`: +Você quer fazer com que sempre que o usuário altere as entradas do formulário, o state atualize para refletir essas mudanças. O state é possuído por `FilterableProductTable`, então apenas ele pode chamar `setFilterText` e `setInStockOnly`. Para permitir que `SearchBar` atualize o state de `FilterableProductTable`, você precisa passar essas funções para `SearchBar`: ```js {2,3,10,11} function FilterableProductTable({ products }) { @@ -482,7 +481,7 @@ function FilterableProductTable({ products }) { onInStockOnlyChange={setInStockOnly} /> ``` -Inside the `SearchBar`, you will add the `onChange` event handlers and set the parent state from them: +Dentro do `SearchBar`, você adicionará os manipuladores de evento `onChange` e definirá o state pai a partir deles: ```js {4,5,13,19} function SearchBar({ @@ -506,7 +505,7 @@ function SearchBar({ onChange={(e) => onInStockOnlyChange(e.target.checked)} ``` -Now the application fully works! +Agora a aplicação funciona completamente! @@ -656,8 +655,8 @@ td { -You can learn all about handling events and updating state in the [Adding Interactivity](/learn/adding-interactivity) section. +Você pode aprender tudo sobre manipulação de eventos e atualização de state na seção [Adicionando Interatividade](/learn/adding-interactivity). -## Where to go from here {/*where-to-go-from-here*/} +## Para onde ir daqui {/*where-to-go-from-here*/} -This was a very brief introduction to how to think about building components and applications with React. You can [start a React project](/learn/installation) right now or [dive deeper on all the syntax](/learn/describing-the-ui) used in this tutorial. +Esta foi uma introdução muito breve sobre como pensar sobre construir componentes e aplicações com React. Você pode [iniciar um projeto React](/learn/installation) agora mesmo ou [mergulhar mais fundo em toda a sintaxe](/learn/describing-the-ui) usada neste tutorial. \ No newline at end of file From 51ed1657671a4a63fa43123297493f73420c39d6 Mon Sep 17 00:00:00 2001 From: manuel Date: Mon, 23 Jun 2025 17:03:19 +0100 Subject: [PATCH 2/2] feat(docs): translate "Creating a React App" and "Build a React app from Scratch" to Portuguese --- .../learn/build-a-react-app-from-scratch.md | 105 +++++++++--------- src/content/learn/creating-a-react-app.md | 71 ++++++------ 2 files changed, 86 insertions(+), 90 deletions(-) diff --git a/src/content/learn/build-a-react-app-from-scratch.md b/src/content/learn/build-a-react-app-from-scratch.md index 721f670dd..2d1d5831f 100644 --- a/src/content/learn/build-a-react-app-from-scratch.md +++ b/src/content/learn/build-a-react-app-from-scratch.md @@ -1,143 +1,140 @@ --- -title: Build a React app from Scratch +title: Construir uma Aplicação React do Zero --- -If your app has constraints not well-served by existing frameworks, you prefer to build your own framework, or you just want to learn the basics of a React app, you can build a React app from scratch. +Se sua aplicação tem restrições que não são bem atendidas pelos frameworks existentes, você prefere construir seu próprio framework, ou apenas quer aprender o básico de uma aplicação React, você pode construir uma aplicação React do zero. -#### Consider using a framework {/*consider-using-a-framework*/} +#### Considere usar um framework {/*consider-using-a-framework*/} -Starting from scratch is an easy way to get started using React, but a major tradeoff to be aware of is that going this route is often the same as building your own adhoc framework. As your requirements evolve, you may need to solve more framework-like problems that our recommended frameworks already have well developed and supported solutions for. +Começar do zero é uma maneira fácil de começar a usar React, mas um compromisso importante a ter em mente é que seguir este caminho é muitas vezes o mesmo que construir seu próprio framework ad hoc. À medida que seus requisitos evoluem, você pode precisar resolver mais problemas semelhantes a frameworks para os quais nossos frameworks recomendados já têm soluções bem desenvolvidas e suportadas. -For example, if in the future your app needs support for server-side rendering (SSR), static site generation (SSG), and/or React Server Components (RSC), you will have to implement those on your own. Similarly, future React features that require integrating at the framework level will have to be implemented on your own if you want to use them. +Por exemplo, se no futuro sua aplicação precisar de suporte para renderização do lado do servidor (SSR), geração de site estático (SSG), e/ou React Server Components (RSC), você terá que implementá-los por conta própria. Da mesma forma, futuras funcionalidades do React que requerem integração no nível do framework terão que ser implementadas por você se quiser usá-las. -Our recommended frameworks also help you build better performing apps. For example, reducing or eliminating waterfalls from network requests makes for a better user experience. This might not be a high priority when you are building a toy project, but if your app gains users you may want to improve its performance. +Nossos frameworks recomendados também ajudam você a construir aplicações com melhor performance. Por exemplo, reduzir ou eliminar cascatas de requisições de rede proporciona uma melhor experiência do usuário. Isso pode não ser uma alta prioridade quando você está construindo um projeto de teste, mas se sua aplicação ganhar usuários, você pode querer melhorar sua performance. -Going this route also makes it more difficult to get support, since the way you develop routing, data-fetching, and other features will be unique to your situation. You should only choose this option if you are comfortable tackling these problems on your own, or if you’re confident that you will never need these features. +Seguir este caminho também torna mais difícil obter suporte, já que a maneira como você desenvolve roteamento, busca de dados e outras funcionalidades será única para sua situação. Você deve escolher esta opção apenas se estiver confortável em lidar com esses problemas por conta própria, ou se estiver confiante de que nunca precisará dessas funcionalidades. -For a list of recommended frameworks, check out [Creating a React App](/learn/creating-a-react-app). +Para uma lista de frameworks recomendados, confira [Criando uma Aplicação React](/learn/creating-a-react-app). +## Passo 1: Instalar uma ferramenta de build {/*step-1-install-a-build-tool*/} -## Step 1: Install a build tool {/*step-1-install-a-build-tool*/} - -The first step is to install a build tool like `vite`, `parcel`, or `rsbuild`. These build tools provide features to package and run source code, provide a development server for local development and a build command to deploy your app to a production server. +O primeiro passo é instalar uma ferramenta de build como `vite`, `parcel`, ou `rsbuild`. Essas ferramentas de build fornecem funcionalidades para empacotar e executar código fonte, fornecem um servidor de desenvolvimento para desenvolvimento local e um comando de build para fazer deploy da sua aplicação em um servidor de produção. ### Vite {/*vite*/} -[Vite](https://vite.dev/) is a build tool that aims to provide a faster and leaner development experience for modern web projects. +[Vite](https://vite.dev/) é uma ferramenta de build que visa fornecer uma experiência de desenvolvimento mais rápida e enxuta para projetos web modernos. {`npm create vite@latest my-app -- --template react`} -Vite is opinionated and comes with sensible defaults out of the box. Vite has a rich ecosystem of plugins to support fast refresh, JSX, Babel/SWC, and other common features. See Vite's [React plugin](https://vite.dev/plugins/#vitejs-plugin-react) or [React SWC plugin](https://vite.dev/plugins/#vitejs-plugin-react-swc) and [React SSR example project](https://vite.dev/guide/ssr.html#example-projects) to get started. +Vite é opinativo e vem com padrões sensatos prontos para uso. Vite tem um rico ecossistema de plugins para suportar fast refresh, JSX, Babel/SWC, e outras funcionalidades comuns. Veja o [plugin React do Vite](https://vite.dev/plugins/#vitejs-plugin-react) ou [plugin React SWC](https://vite.dev/plugins/#vitejs-plugin-react-swc) e [projeto de exemplo React SSR](https://vite.dev/guide/ssr.html#example-projects) para começar. -Vite is already being used as a build tool in one of our [recommended frameworks](/learn/creating-a-react-app): [React Router](https://reactrouter.com/start/framework/installation). +Vite já está sendo usado como ferramenta de build em um dos nossos [frameworks recomendados](/learn/creating-a-react-app): [React Router](https://reactrouter.com/start/framework/installation). ### Parcel {/*parcel*/} -[Parcel](https://parceljs.org/) combines a great out-of-the-box development experience with a scalable architecture that can take your project from just getting started to massive production applications. +[Parcel](https://parceljs.org/) combina uma ótima experiência de desenvolvimento pronta para uso com uma arquitetura escalável que pode levar seu projeto desde o início até aplicações de produção massivas. {`npm install --save-dev parcel`} -Parcel supports fast refresh, JSX, TypeScript, Flow, and styling out of the box. See [Parcel's React recipe](https://parceljs.org/recipes/react/#getting-started) to get started. +Parcel suporta fast refresh, JSX, TypeScript, Flow, e estilização prontos para uso. Veja a [receita React do Parcel](https://parceljs.org/recipes/react/#getting-started) para começar. ### Rsbuild {/*rsbuild*/} -[Rsbuild](https://rsbuild.dev/) is an Rspack-powered build tool that provides a seamless development experience for React applications. It comes with carefully tuned defaults and performance optimizations ready to use. +[Rsbuild](https://rsbuild.dev/) é uma ferramenta de build alimentada pelo Rspack que fornece uma experiência de desenvolvimento perfeita para aplicações React. Vem com padrões cuidadosamente ajustados e otimizações de performance prontas para uso. {`npx create-rsbuild --template react`} -Rsbuild includes built-in support for React features like fast refresh, JSX, TypeScript, and styling. See [Rsbuild's React guide](https://rsbuild.dev/guide/framework/react) to get started. +Rsbuild inclui suporte integrado para funcionalidades React como fast refresh, JSX, TypeScript, e estilização. Veja o [guia React do Rsbuild](https://rsbuild.dev/guide/framework/react) para começar. -#### Metro for React Native {/*react-native*/} +#### Metro para React Native {/*react-native*/} -If you're starting from scratch with React Native you'll need to use [Metro](https://metrobundler.dev/), the JavaScript bundler for React Native. Metro supports bundling for platforms like iOS and Android, but lacks many features when compared to the tools here. We recommend starting with Vite, Parcel, or Rsbuild unless your project requires React Native support. +Se você está começando do zero com React Native, precisará usar o [Metro](https://metrobundler.dev/), o bundler JavaScript para React Native. Metro suporta bundling para plataformas como iOS e Android, mas carece de muitas funcionalidades quando comparado às ferramentas aqui. Recomendamos começar com Vite, Parcel, ou Rsbuild, a menos que seu projeto requeira suporte ao React Native. -## Step 2: Build Common Application Patterns {/*step-2-build-common-application-patterns*/} +## Passo 2: Construir Padrões Comuns de Aplicação {/*step-2-build-common-application-patterns*/} -The build tools listed above start off with a client-only, single-page app (SPA), but don't include any further solutions for common functionality like routing, data fetching, or styling. +As ferramentas de build listadas acima começam com uma aplicação de página única (SPA) apenas do lado do cliente, mas não incluem soluções adicionais para funcionalidades comuns como roteamento, busca de dados, ou estilização. -The React ecosystem includes many tools for these problems. We've listed a few that are widely used as a starting point, but feel free to choose other tools if those work better for you. +O ecossistema React inclui muitas ferramentas para esses problemas. Listamos algumas que são amplamente usadas como ponto de partida, mas sinta-se livre para escolher outras ferramentas se funcionarem melhor para você. -### Routing {/*routing*/} +### Roteamento {/*routing*/} -Routing determines what content or pages to display when a user visits a particular URL. You need to set up a router to map URLs to different parts of your app. You'll also need to handle nested routes, route parameters, and query parameters. Routers can be configured within your code, or defined based on your component folder and file structures. +Roteamento determina qual conteúdo ou páginas exibir quando um usuário visita uma URL específica. Você precisa configurar um roteador para mapear URLs para diferentes partes da sua aplicação. Você também precisará lidar com rotas aninhadas, parâmetros de rota e parâmetros de consulta. Os roteadores podem ser configurados dentro do seu código, ou definidos com base nas estruturas de pastas e arquivos dos seus componentes. -Routers are a core part of modern applications, and are usually integrated with data fetching (including prefetching data for a whole page for faster loading), code splitting (to minimize client bundle sizes), and page rendering approaches (to decide how each page gets generated). +Os roteadores são uma parte central das aplicações modernas, e geralmente são integrados com busca de dados (incluindo pré-busca de dados para uma página inteira para carregamento mais rápido), divisão de código (para minimizar tamanhos de bundle do cliente), e abordagens de renderização de página (para decidir como cada página é gerada). -We suggest using: +Sugerimos usar: - [React Router](https://reactrouter.com/start/data/custom) - [Tanstack Router](https://tanstack.com/router/latest) +### Busca de Dados {/*data-fetching*/} -### Data Fetching {/*data-fetching*/} - -Fetching data from a server or other data source is a key part of most applications. Doing this properly requires handling loading states, error states, and caching the fetched data, which can be complex. +Buscar dados de um servidor ou outra fonte de dados é uma parte fundamental da maioria das aplicações. Fazer isso adequadamente requer lidar com estados de carregamento, estados de erro, e cache dos dados buscados, que pode ser complexo. -Purpose-built data fetching libraries do the hard work of fetching and caching the data for you, letting you focus on what data your app needs and how to display it. These libraries are typically used directly in your components, but can also be integrated into routing loaders for faster pre-fetching and better performance, and in server rendering as well. +Bibliotecas de busca de dados especializadas fazem o trabalho pesado de buscar e cachear os dados para você, permitindo que você se concentre em quais dados sua aplicação precisa e como exibi-los. Essas bibliotecas são tipicamente usadas diretamente nos seus componentes, mas também podem ser integradas em loaders de roteamento para pré-busca mais rápida e melhor performance, e também na renderização do servidor. -Note that fetching data directly in components can lead to slower loading times due to network request waterfalls, so we recommend prefetching data in router loaders or on the server as much as possible! This allows a page's data to be fetched all at once as the page is being displayed. +Note que buscar dados diretamente nos componentes pode levar a tempos de carregamento mais lentos devido a cascatas de requisições de rede, então recomendamos pré-buscar dados em loaders de roteador ou no servidor o máximo possível! Isso permite que os dados de uma página sejam buscados todos de uma vez conforme a página está sendo exibida. -If you're fetching data from most backends or REST-style APIs, we suggest using: +Se você está buscando dados da maioria dos backends ou APIs estilo REST, sugerimos usar: - [React Query](https://react-query.tanstack.com/) - [SWR](https://swr.vercel.app/) - [RTK Query](https://redux-toolkit.js.org/rtk-query/overview) -If you're fetching data from a GraphQL API, we suggest using: +Se você está buscando dados de uma API GraphQL, sugerimos usar: - [Apollo](https://www.apollographql.com/docs/react) - [Relay](https://relay.dev/) +### Divisão de Código {/*code-splitting*/} -### Code-splitting {/*code-splitting*/} - -Code-splitting is the process of breaking your app into smaller bundles that can be loaded on demand. An app's code size increases with every new feature and additional dependency. Apps can become slow to load because all of the code for the entire app needs to be sent before it can be used. Caching, reducing features/dependencies, and moving some code to run on the server can help mitigate slow loading but are incomplete solutions that can sacrifice functionality if overused. +Divisão de código é o processo de quebrar sua aplicação em bundles menores que podem ser carregados sob demanda. O tamanho do código de uma aplicação aumenta com cada nova funcionalidade e dependência adicional. As aplicações podem se tornar lentas para carregar porque todo o código para a aplicação inteira precisa ser enviado antes que possa ser usado. Cache, redução de funcionalidades/dependências, e mover algum código para executar no servidor podem ajudar a mitigar o carregamento lento, mas são soluções incompletas que podem sacrificar funcionalidade se usadas em excesso. -Similarly, if you rely on the apps using your framework to split the code, you might encounter situations where loading becomes slower than if no code splitting were happening at all. For example, [lazily loading](/reference/react/lazy) a chart delays sending the code needed to render the chart, splitting the chart code from the rest of the app. [Parcel supports code splitting with React.lazy](https://parceljs.org/recipes/react/#code-splitting). However, if the chart loads its data *after* it has been initially rendered you are now waiting twice. This is a waterfall: rather than fetching the data for the chart and sending the code to render it simultaneously, you must wait for each step to complete one after the other. +Da mesma forma, se você depende das aplicações que usam seu framework para dividir o código, você pode encontrar situações onde o carregamento se torna mais lento do que se nenhuma divisão de código estivesse acontecendo. Por exemplo, [carregar preguiçosamente](/reference/react/lazy) um gráfico atrasa o envio do código necessário para renderizar o gráfico, dividindo o código do gráfico do resto da aplicação. [Parcel suporta divisão de código com React.lazy](https://parceljs.org/recipes/react/#code-splitting). No entanto, se o gráfico carrega seus dados *depois* que foi inicialmente renderizado, você agora está esperando duas vezes. Esta é uma cascata: ao invés de buscar os dados para o gráfico e enviar o código para renderizá-lo simultaneamente, você deve esperar cada passo completar um após o outro. -Splitting code by route, when integrated with bundling and data fetching, can reduce the initial load time of your app and the time it takes for the largest visible content of the app to render ([Largest Contentful Paint](https://web.dev/articles/lcp)). +Dividir código por rota, quando integrado com bundling e busca de dados, pode reduzir o tempo de carregamento inicial da sua aplicação e o tempo que leva para o maior conteúdo visível da aplicação renderizar ([Largest Contentful Paint](https://web.dev/articles/lcp)). -For code-splitting instructions, see your build tool docs: -- [Vite build optimizations](https://v3.vitejs.dev/guide/features.html#build-optimizations) -- [Parcel code splitting](https://parceljs.org/features/code-splitting/) -- [Rsbuild code splitting](https://rsbuild.dev/guide/optimization/code-splitting) +Para instruções de divisão de código, veja a documentação da sua ferramenta de build: +- [Otimizações de build do Vite](https://v3.vitejs.dev/guide/features.html#build-optimizations) +- [Divisão de código do Parcel](https://parceljs.org/features/code-splitting/) +- [Divisão de código do Rsbuild](https://rsbuild.dev/guide/optimization/code-splitting) -### Improving Application Performance {/*improving-application-performance*/} +### Melhorando a Performance da Aplicação {/*improving-application-performance*/} -Since the build tool you select only support single page apps (SPAs) you'll need to implement other [rendering patterns](https://www.patterns.dev/vanilla/rendering-patterns) like server-side rendering (SSR), static site generation (SSG), and/or React Server Components (RSC). Even if you don't need these features at first, in the future there may be some routes that would benefit SSR, SSG or RSC. +Como a ferramenta de build que você seleciona só suporta aplicações de página única (SPAs), você precisará implementar outros [padrões de renderização](https://www.patterns.dev/vanilla/rendering-patterns) como renderização do lado do servidor (SSR), geração de site estático (SSG), e/ou React Server Components (RSC). Mesmo se você não precisar dessas funcionalidades no início, no futuro pode haver algumas rotas que se beneficiariam de SSR, SSG ou RSC. -* **Single-page apps (SPA)** load a single HTML page and dynamically updates the page as the user interacts with the app. SPAs are easier to get started with, but they can have slower initial load times. SPAs are the default architecture for most build tools. +* **Aplicações de página única (SPA)** carregam uma única página HTML e atualizam dinamicamente a página conforme o usuário interage com a aplicação. SPAs são mais fáceis de começar, mas podem ter tempos de carregamento inicial mais lentos. SPAs são a arquitetura padrão para a maioria das ferramentas de build. -* **Streaming Server-side rendering (SSR)** renders a page on the server and sends the fully rendered page to the client. SSR can improve performance, but it can be more complex to set up and maintain than a single-page app. With the addition of streaming, SSR can be very complex to set up and maintain. See [Vite's SSR guide]( https://vite.dev/guide/ssr). +* **Renderização do lado do servidor com streaming (SSR)** renderiza uma página no servidor e envia a página totalmente renderizada para o cliente. SSR pode melhorar a performance, mas pode ser mais complexo de configurar e manter do que uma aplicação de página única. Com a adição de streaming, SSR pode ser muito complexo de configurar e manter. Veja o [guia SSR do Vite](https://vite.dev/guide/ssr). -* **Static site generation (SSG)** generates static HTML files for your app at build time. SSG can improve performance, but it can be more complex to set up and maintain than server-side rendering. See [Vite's SSG guide](https://vite.dev/guide/ssr.html#pre-rendering-ssg). +* **Geração de site estático (SSG)** gera arquivos HTML estáticos para sua aplicação no momento do build. SSG pode melhorar a performance, mas pode ser mais complexo de configurar e manter do que renderização do lado do servidor. Veja o [guia SSG do Vite](https://vite.dev/guide/ssr.html#pre-rendering-ssg). -* **React Server Components (RSC)** lets you mix build-time, server-only, and interactive components in a single React tree. RSC can improve performance, but it currently requires deep expertise to set up and maintain. See [Parcel's RSC examples](https://github.com/parcel-bundler/rsc-examples). +* **React Server Components (RSC)** permite misturar componentes de build-time, apenas do servidor, e interativos em uma única árvore React. RSC pode melhorar a performance, mas atualmente requer expertise profunda para configurar e manter. Veja os [exemplos RSC do Parcel](https://github.com/parcel-bundler/rsc-examples). -Your rendering strategies need to integrate with your router so apps built with your framework can choose the rendering strategy on a per-route level. This will enable different rendering strategies without having to rewrite your whole app. For example, the landing page for your app might benefit from being statically generated (SSG), while a page with a content feed might perform best with server-side rendering. +Suas estratégias de renderização precisam se integrar com seu roteador para que aplicações construídas com seu framework possam escolher a estratégia de renderização no nível de rota. Isso permitirá diferentes estratégias de renderização sem ter que reescrever toda a sua aplicação. Por exemplo, a página de destino da sua aplicação pode se beneficiar de ser gerada estaticamente (SSG), enquanto uma página com um feed de conteúdo pode ter melhor performance com renderização do lado do servidor. -Using the right rendering strategy for the right routes can decrease the time it takes for the first byte of content to be loaded ([Time to First Byte](https://web.dev/articles/ttfb)), the first piece of content to render ([First Contentful Paint](https://web.dev/articles/fcp)), and the largest visible content of the app to render ([Largest Contentful Paint](https://web.dev/articles/lcp)). +Usar a estratégia de renderização certa para as rotas certas pode diminuir o tempo que leva para o primeiro byte de conteúdo ser carregado ([Time to First Byte](https://web.dev/articles/ttfb)), o primeiro pedaço de conteúdo renderizar ([First Contentful Paint](https://web.dev/articles/fcp)), e o maior conteúdo visível da aplicação renderizar ([Largest Contentful Paint](https://web.dev/articles/lcp)). -### And more... {/*and-more*/} +### E mais... {/*and-more*/} -These are just a few examples of the features a new app will need to consider when building from scratch. Many limitations you'll hit can be difficult to solve as each problem is interconnected with the others and can require deep expertise in problem areas you may not be familiar with. +Estes são apenas alguns exemplos das funcionalidades que uma nova aplicação precisará considerar ao construir do zero. Muitas limitações que você encontrará podem ser difíceis de resolver, já que cada problema está interconectado com os outros e pode requerer expertise profunda em áreas problemáticas com as quais você pode não estar familiarizado. -If you don't want to solve these problems on your own, you can [get started with a framework](/learn/creating-a-react-app) that provides these features out of the box. +Se você não quer resolver esses problemas por conta própria, pode [começar com um framework](/learn/creating-a-react-app) que fornece essas funcionalidades prontas para uso. \ No newline at end of file diff --git a/src/content/learn/creating-a-react-app.md b/src/content/learn/creating-a-react-app.md index fc6c956d4..e49234221 100644 --- a/src/content/learn/creating-a-react-app.md +++ b/src/content/learn/creating-a-react-app.md @@ -1,94 +1,93 @@ --- -title: Creating a React App +title: Criando uma Aplicação React --- -If you want to build a new app or website with React, we recommend starting with a framework. +Se você quer construir uma nova aplicação ou website com React, recomendamos começar com um framework. -If your app has constraints not well-served by existing frameworks, you prefer to build your own framework, or you just want to learn the basics of a React app, you can [build a React app from scratch](/learn/build-a-react-app-from-scratch). +Se sua aplicação tem restrições que não são bem atendidas pelos frameworks existentes, você prefere construir seu próprio framework, ou apenas quer aprender o básico de uma aplicação React, você pode [construir uma aplicação React do zero](/learn/build-a-react-app-from-scratch). -## Full-stack frameworks {/*full-stack-frameworks*/} +## Frameworks full-stack {/*full-stack-frameworks*/} -These recommended frameworks support all the features you need to deploy and scale your app in production. They have integrated the latest React features and take advantage of React’s architecture. +Estes frameworks recomendados suportam todas as funcionalidades que você precisa para fazer deploy e escalar sua aplicação em produção. Eles integraram as funcionalidades mais recentes do React e aproveitam a arquitetura do React. -#### Full-stack frameworks do not require a server. {/*react-frameworks-do-not-require-a-server*/} +#### Frameworks full-stack não requerem um servidor. {/*react-frameworks-do-not-require-a-server*/} -All the frameworks on this page support client-side rendering ([CSR](https://developer.mozilla.org/en-US/docs/Glossary/CSR)), single-page apps ([SPA](https://developer.mozilla.org/en-US/docs/Glossary/SPA)), and static-site generation ([SSG](https://developer.mozilla.org/en-US/docs/Glossary/SSG)). These apps can be deployed to a [CDN](https://developer.mozilla.org/en-US/docs/Glossary/CDN) or static hosting service without a server. Additionally, these frameworks allow you to add server-side rendering on a per-route basis, when it makes sense for your use case. +Todos os frameworks nesta página suportam renderização do lado do cliente ([CSR](https://developer.mozilla.org/en-US/docs/Glossary/CSR)), aplicações de página única ([SPA](https://developer.mozilla.org/en-US/docs/Glossary/SPA)), e geração de site estático ([SSG](https://developer.mozilla.org/en-US/docs/Glossary/SSG)). Essas aplicações podem ser deployadas em uma [CDN](https://developer.mozilla.org/en-US/docs/Glossary/CDN) ou serviço de hospedagem estática sem um servidor. Além disso, esses frameworks permitem que você adicione renderização do lado do servidor rota por rota, quando faz sentido para seu caso de uso. -This allows you to start with a client-only app, and if your needs change later, you can opt-in to using server features on individual routes without rewriting your app. See your framework's documentation for configuring the rendering strategy. +Isso permite que você comece com uma aplicação apenas do lado do cliente, e se suas necessidades mudarem depois, você pode optar por usar funcionalidades de servidor em rotas individuais sem reescrever sua aplicação. Veja a documentação do seu framework para configurar a estratégia de renderização. ### Next.js (App Router) {/*nextjs-app-router*/} -**[Next.js's App Router](https://nextjs.org/docs) is a React framework that takes full advantage of React's architecture to enable full-stack React apps.** +**[O App Router do Next.js](https://nextjs.org/docs) é um framework React que aproveita completamente a arquitetura do React para permitir aplicações React full-stack.** npx create-next-app@latest -Next.js is maintained by [Vercel](https://vercel.com/). You can [deploy a Next.js app](https://nextjs.org/docs/app/building-your-application/deploying) to any Node.js or serverless hosting, or to your own server. Next.js also supports [static export](https://nextjs.org/docs/app/building-your-application/deploying/static-exports) which doesn't require a server. Vercel additionally provides opt-in paid cloud services. +Next.js é mantido pela [Vercel](https://vercel.com/). Você pode [fazer deploy de uma aplicação Next.js](https://nextjs.org/docs/app/building-your-application/deploying) para qualquer hospedagem Node.js ou serverless, ou para seu próprio servidor. Next.js também suporta [exportação estática](https://nextjs.org/docs/app/building-your-application/deploying/static-exports) que não requer um servidor. A Vercel também fornece serviços em nuvem pagos opcionais. ### React Router (v7) {/*react-router-v7*/} -**[React Router](https://reactrouter.com/start/framework/installation) is the most popular routing library for React and can be paired with Vite to create a full-stack React framework**. It emphasizes standard Web APIs and has several [ready to deploy templates](https://github.com/remix-run/react-router-templates) for various JavaScript runtimes and platforms. +**[React Router](https://reactrouter.com/start/framework/installation) é a biblioteca de roteamento mais popular para React e pode ser pareada com Vite para criar um framework React full-stack**. Ele enfatiza APIs Web padrão e tem vários [templates prontos para deploy](https://github.com/remix-run/react-router-templates) para vários runtimes JavaScript e plataformas. -To create a new React Router framework project, run: +Para criar um novo projeto de framework React Router, execute: npx create-react-router@latest -React Router is maintained by [Shopify](https://www.shopify.com). +React Router é mantido pela [Shopify](https://www.shopify.com). -### Expo (for native apps) {/*expo*/} +### Expo (para aplicações nativas) {/*expo*/} -**[Expo](https://expo.dev/) is a React framework that lets you create universal Android, iOS, and web apps with truly native UIs.** It provides an SDK for [React Native](https://reactnative.dev/) that makes the native parts easier to use. To create a new Expo project, run: +**[Expo](https://expo.dev/) é um framework React que permite criar aplicações universais para Android, iOS, e web com interfaces verdadeiramente nativas.** Ele fornece um SDK para [React Native](https://reactnative.dev/) que torna as partes nativas mais fáceis de usar. Para criar um novo projeto Expo, execute: npx create-expo-app@latest -If you're new to Expo, check out the [Expo tutorial](https://docs.expo.dev/tutorial/introduction/). +Se você é novo no Expo, confira o [tutorial do Expo](https://docs.expo.dev/tutorial/introduction/). -Expo is maintained by [Expo (the company)](https://expo.dev/about). Building apps with Expo is free, and you can submit them to the Google and Apple app stores without restrictions. Expo additionally provides opt-in paid cloud services. +Expo é mantido pela [Expo (a empresa)](https://expo.dev/about). Construir aplicações com Expo é gratuito, e você pode enviá-las para as app stores do Google e Apple sem restrições. Expo também fornece serviços em nuvem pagos opcionais. +## Outros frameworks {/*other-frameworks*/} -## Other frameworks {/*other-frameworks*/} +Existem outros frameworks emergentes que estão trabalhando em direção à nossa visão de React full-stack: -There are other up-and-coming frameworks that are working towards our full stack React vision: - -- [TanStack Start (Beta)](https://tanstack.com/): TanStack Start is a full-stack React framework powered by TanStack Router. It provides a full-document SSR, streaming, server functions, bundling, and more using tools like Nitro and Vite. -- [RedwoodJS](https://redwoodjs.com/): Redwood is a full stack React framework with lots of pre-installed packages and configuration that makes it easy to build full-stack web applications. +- [TanStack Start (Beta)](https://tanstack.com/): TanStack Start é um framework React full-stack alimentado pelo TanStack Router. Ele fornece SSR de documento completo, streaming, funções de servidor, bundling, e mais usando ferramentas como Nitro e Vite. +- [RedwoodJS](https://redwoodjs.com/): Redwood é um framework React full-stack com muitos pacotes pré-instalados e configuração que torna fácil construir aplicações web full-stack. -#### Which features make up the React team’s full-stack architecture vision? {/*which-features-make-up-the-react-teams-full-stack-architecture-vision*/} +#### Quais funcionalidades compõem a visão de arquitetura full-stack da equipe React? {/*which-features-make-up-the-react-teams-full-stack-architecture-vision*/} -Next.js's App Router bundler fully implements the official [React Server Components specification](https://github.com/reactjs/rfcs/blob/main/text/0188-server-components.md). This lets you mix build-time, server-only, and interactive components in a single React tree. +O bundler App Router do Next.js implementa completamente a [especificação oficial dos React Server Components](https://github.com/reactjs/rfcs/blob/main/text/0188-server-components.md). Isso permite misturar componentes de build-time, apenas do servidor, e interativos em uma única árvore React. -For example, you can write a server-only React component as an `async` function that reads from a database or from a file. Then you can pass data down from it to your interactive components: +Por exemplo, você pode escrever um componente React apenas do servidor como uma função `async` que lê de um banco de dados ou de um arquivo. Então você pode passar dados para baixo para seus componentes interativos: ```js -// This component runs *only* on the server (or during the build). +// Este componente executa *apenas* no servidor (ou durante o build). async function Talks({ confId }) { - // 1. You're on the server, so you can talk to your data layer. API endpoint not required. + // 1. Você está no servidor, então pode conversar com sua camada de dados. Endpoint de API não é necessário. const talks = await db.Talks.findAll({ confId }); - // 2. Add any amount of rendering logic. It won't make your JavaScript bundle larger. + // 2. Adicione qualquer quantidade de lógica de renderização. Isso não tornará seu bundle JavaScript maior. const videos = talks.map(talk => talk.video); - // 3. Pass the data down to the components that will run in the browser. + // 3. Passe os dados para baixo para os componentes que executarão no navegador. return ; } ``` -Next.js's App Router also integrates [data fetching with Suspense](/blog/2022/03/29/react-v18#suspense-in-data-frameworks). This lets you specify a loading state (like a skeleton placeholder) for different parts of your user interface directly in your React tree: +O App Router do Next.js também integra [busca de dados com Suspense](/blog/2022/03/29/react-v18#suspense-in-data-frameworks). Isso permite especificar um estado de carregamento (como um placeholder skeleton) para diferentes partes da sua interface de usuário diretamente na sua árvore React: ```js }> @@ -96,18 +95,18 @@ Next.js's App Router also integrates [data fetching with Suspense](/blog/2022/03 ``` -Server Components and Suspense are React features rather than Next.js features. However, adopting them at the framework level requires buy-in and non-trivial implementation work. At the moment, the Next.js App Router is the most complete implementation. The React team is working with bundler developers to make these features easier to implement in the next generation of frameworks. +Server Components e Suspense são funcionalidades do React ao invés de funcionalidades do Next.js. No entanto, adotá-las no nível do framework requer buy-in e trabalho de implementação não trivial. No momento, o App Router do Next.js é a implementação mais completa. A equipe React está trabalhando com desenvolvedores de bundlers para tornar essas funcionalidades mais fáceis de implementar na próxima geração de frameworks. -## Start From Scratch {/*start-from-scratch*/} +## Começar do Zero {/*start-from-scratch*/} -If your app has constraints not well-served by existing frameworks, you prefer to build your own framework, or you just want to learn the basics of a React app, there are other options available for starting a React project from scratch. +Se sua aplicação tem restrições que não são bem atendidas pelos frameworks existentes, você prefere construir seu próprio framework, ou apenas quer aprender o básico de uma aplicação React, existem outras opções disponíveis para começar um projeto React do zero. -Starting from scratch gives you more flexibility, but does require that you make choices on which tools to use for routing, data fetching, and other common usage patterns. It's a lot like building your own framework, instead of using a framework that already exists. The [frameworks we recommend](#full-stack-frameworks) have built-in solutions for these problems. +Começar do zero te dá mais flexibilidade, mas requer que você faça escolhas sobre quais ferramentas usar para roteamento, busca de dados, e outros padrões de uso comuns. É muito parecido com construir seu próprio framework, ao invés de usar um framework que já existe. Os [frameworks que recomendamos](#full-stack-frameworks) têm soluções integradas para esses problemas. -If you want to build your own solutions, see our guide to [build a React app from Scratch](/learn/build-a-react-app-from-scratch) for instructions on how to set up a new React project starting with a built tool like [Vite](https://vite.dev/), [Parcel](https://parceljs.org/), or [RSbuild](https://rsbuild.dev/). +Se você quer construir suas próprias soluções, veja nosso guia para [construir uma aplicação React do Zero](/learn/build-a-react-app-from-scratch) para instruções sobre como configurar um novo projeto React começando com uma ferramenta de build como [Vite](https://vite.dev/), [Parcel](https://parceljs.org/), ou [RSbuild](https://rsbuild.dev/). ----- -_If you’re a framework author interested in being included on this page, [please let us know](https://github.com/reactjs/react.dev/issues/new?assignees=&labels=type%3A+framework&projects=&template=3-framework.yml&title=%5BFramework%5D%3A+)._ +_Se você é um autor de framework interessado em ser incluído nesta página, [por favor nos informe](https://github.com/reactjs/react.dev/issues/new?assignees=&labels=type%3A+framework&projects=&template=3-framework.yml&title=%5BFramework%5D%3A+)._ \ No newline at end of file