diff --git a/src/content/reference/react-dom/components/form.md b/src/content/reference/react-dom/components/form.md index 8f6ab00e0..2c0f8fc8a 100644 --- a/src/content/reference/react-dom/components/form.md +++ b/src/content/reference/react-dom/components/form.md @@ -5,19 +5,19 @@ canary: true -React's extensions to `
` are currently only available in React's canary and experimental channels. In stable releases of React, `` works only as a [built-in browser HTML component](https://react.dev/reference/react-dom/components#all-html-components). Learn more about [React's release channels here](/community/versioning-policy#all-release-channels). +As extensões do React para `` estão atualmente disponíveis apenas nos canais canary e experimental do React. Nas versões estáveis do React, `` funciona apenas como um [componente HTML embutido do navegador](https://react.dev/reference/react-dom/components#all-html-components). Saiba mais sobre [os canais de lançamento do React aqui](/community/versioning-policy#all-release-channels). -The [built-in browser `` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) lets you create interactive controls for submitting information. +O [componente `` embutido do navegador](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) permite criar controles interativos para enviar informações. ```js - + ``` @@ -27,38 +27,38 @@ The [built-in browser `
` component](https://developer.mozilla.org/en-US/do --- -## Reference {/*reference*/} +## Referência {/*reference*/} ### `` {/*form*/} -To create interactive controls for submitting information, render the [built-in browser `` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form). +Para criar controles interativos para enviar informações, renderize o [componente `` embutido do navegador](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form). ```js - +
``` -[See more examples below.](#usage) +[Veja mais exemplos abaixo.](#usage) #### Props {/*props*/} -`
` supports all [common element props.](/reference/react-dom/components/common#props) +`` suporta todas as [props comuns de elementos.](/reference/react-dom/components/common#props) -[`action`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#action): a URL or function. When a URL is passed to `action` the form will behave like the HTML form component. When a function is passed to `action` the function will handle the form submission. The function passed to `action` may be async and will be called with a single argument containing the [form data](https://developer.mozilla.org/en-US/docs/Web/API/FormData) of the submitted form. The `action` prop can be overridden by a `formAction` attribute on a ` +
); } @@ -91,13 +91,13 @@ export default function Search() { -### Handle form submission with a Server Action {/*handle-form-submission-with-a-server-action*/} +### Lidar com o envio do formulário com uma Ação do Servidor {/*handle-form-submission-with-a-server-action*/} -Render a `
` with an input and submit button. Pass a Server Action (a function marked with [`'use server'`](/reference/rsc/use-server)) to the `action` prop of form to run the function when the form is submitted. +Renderize um `` com um campo de entrada e botão de envio. Passe uma Ação do Servidor (uma função marcada com [`'use server'`](/reference/rsc/use-server)) para a prop `action` do formulário para executar a função quando o formulário for enviado. -Passing a Server Action to `` allow users to submit forms without JavaScript enabled or before the code has loaded. This is beneficial to users who have a slow connection, device, or have JavaScript disabled and is similar to the way forms work when a URL is passed to the `action` prop. +Passar uma Ação do Servidor para `` permite que os usuários enviem formulários sem JavaScript habilitado ou antes que o código tenha sido carregado. Isso é benéfico para usuários que têm uma conexão lenta, um dispositivo com pouca capacidade ou têm JavaScript desabilitado, e é semelhante à forma como os formulários funcionam quando uma URL é passada para a prop `action`. -You can use hidden form fields to provide data to the ``'s action. The Server Action will be called with the hidden form field data as an instance of [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData). +Você pode usar campos de formulário ocultos para fornecer dados à ação do ``. A Ação do Servidor será chamada com os dados dos campos de formulário ocultos como uma instância de [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData). ```jsx import { updateCart } from './lib.js'; @@ -111,14 +111,14 @@ function AddToCart({productId}) { return ( - +
); } ``` -In lieu of using hidden form fields to provide data to the `
`'s action, you can call the `bind` method to supply it with extra arguments. This will bind a new argument (`productId`) to the function in addition to the `formData` that is passed as an argument to the function. +Em vez de usar campos de formulário ocultos para fornecer dados à ação do ``, você pode chamar o `bind` para fornecê-lo com argumentos extras. Isso irá vincular um novo argumento (`productId`) à função, além do `formData` que é passado como um argumento para a função. ```jsx [[1, 8, "bind"], [2,8, "productId"], [2,4, "productId"], [3,4, "formData"]] import { updateCart } from './lib.js'; @@ -131,18 +131,18 @@ function AddToCart({productId}) { const addProductToCart = addToCart.bind(null, productId); return ( - +
); } ``` -When `
` is rendered by a [Server Component](/reference/rsc/use-client), and a [Server Action](/reference/rsc/use-server) is passed to the ``'s `action` prop, the form is [progressively enhanced](https://developer.mozilla.org/en-US/docs/Glossary/Progressive_Enhancement). +Quando `` é renderizado por um [Componente do Servidor](/reference/rsc/use-client), e uma [Ação do Servidor](/reference/rsc/use-server) é passada para a prop `action` do ``, o formulário é [progressivamente aprimorado](https://developer.mozilla.org/en-US/docs/Glossary/Progressive_Enhancement). -### Display a pending state during form submission {/*display-a-pending-state-during-form-submission*/} -To display a pending state when a form is being submitted, you can call the `useFormStatus` Hook in a component rendered in a `` and read the `pending` property returned. +### Exibir um estado de pendência durante o envio do formulário {/*display-a-pending-state-during-form-submission*/} +Para exibir um estado de pendência ao enviar um formulário, você pode chamar o Hook `useFormStatus` em um componente renderizado em um `` e ler a propriedade `pending` retornada. -Here, we use the `pending` property to indicate the form is submitting. +Aqui, usamos a propriedade `pending` para indicar que o formulário está sendo enviado. @@ -154,7 +154,7 @@ function Submit() { const { pending } = useFormStatus(); return ( ); } @@ -191,16 +191,15 @@ export async function submitForm(query) { ``` -To learn more about the `useFormStatus` Hook see the [reference documentation](/reference/react-dom/hooks/useFormStatus). +Para saber mais sobre o Hook `useFormStatus`, consulte a [documentação de referência](/reference/react-dom/hooks/useFormStatus). -### Optimistically updating form data {/*optimistically-updating-form-data*/} -The `useOptimistic` Hook provides a way to optimistically update the user interface before a background operation, like a network request, completes. In the context of forms, this technique helps to make apps feel more responsive. When a user submits a form, instead of waiting for the server's response to reflect the changes, the interface is immediately updated with the expected outcome. +### Atualizando otimisticamente os dados do formulário {/*optimistically-updating-form-data*/} +O Hook `useOptimistic` fornece uma maneira de atualizar otimisticamente a interface do usuário antes que uma operação de segundo plano, como uma requisição de rede, seja concluída. No contexto dos formulários, essa técnica ajuda a tornar os aplicativos mais responsivos. Quando um usuário envia um formulário, em vez de esperar pela resposta do servidor para refletir as alterações, a interface é imediatamente atualizada com o resultado esperado. -For example, when a user types a message into the form and hits the "Send" button, the `useOptimistic` Hook allows the message to immediately appear in the list with a "Sending..." label, even before the message is actually sent to a server. This "optimistic" approach gives the impression of speed and responsiveness. The form then attempts to truly send the message in the background. Once the server confirms the message has been received, the "Sending..." label is removed. +Por exemplo, quando um usuário digita uma mensagem no formulário e pressiona o botão "Enviar", o Hook `useOptimistic` permite que a mensagem apareça imediatamente na lista com um rótulo "Enviando...", mesmo antes da mensagem ser realmente enviada para um servidor. Essa abordagem "otimista" dá a impressão de velocidade e responsividade. O formulário então tenta realmente enviar a mensagem em segundo plano. Assim que o servidor confirma que a mensagem foi recebida, o rótulo "Enviando..." é removido. - ```js src/App.js import { useOptimistic, useState, useRef } from "react"; import { deliverMessage } from "./actions.js"; @@ -228,12 +227,12 @@ function Thread({ messages, sendMessage }) { {optimisticMessages.map((message, index) => (
{message.text} - {!!message.sending && (Sending...)} + {!!message.sending && (Enviando...)}
))} - - + + ); @@ -241,7 +240,7 @@ function Thread({ messages, sendMessage }) { export default function App() { const [messages, setMessages] = useState([ - { text: "Hello there!", sending: false, key: 1 } + { text: "Olá!", sending: false, key: 1 } ]); async function sendMessage(formData) { const sentMessage = await deliverMessage(formData.get("message")); @@ -273,12 +272,12 @@ export async function deliverMessage(message) {
-[//]: # 'Uncomment the next line, and delete this line after the `useOptimistic` reference documentatino page is published' -[//]: # 'To learn more about the `useOptimistic` Hook see the [reference documentation](/reference/react/hooks/useOptimistic).' +[//]: # 'Descomente a próxima linha, e exclua esta linha após a página de documentação de referência `useOptimistic` ser publicada' +[//]: # 'Para saber mais sobre o Hook `useOptimistic`, consulte a [documentação de referência](/reference/react/hooks/useOptimistic).' -### Handling form submission errors {/*handling-form-submission-errors*/} +### Tratando erros de envio do formulário {/*handling-form-submission-errors*/} -In some cases the function called by a `
`'s `action` prop throws an error. You can handle these errors by wrapping `` in an Error Boundary. If the function called by a ``'s `action` prop throws an error, the fallback for the error boundary will be displayed. +Em alguns casos, a função chamada pela prop `action` de um `` lança um erro. Você pode tratar esses erros envolvendo o `` em um Error Boundary. Se a função chamada pela prop `action` de um `` lançar um erro, o fallback para a boundary de erro será exibido. @@ -287,15 +286,15 @@ import { ErrorBoundary } from "react-error-boundary"; export default function Search() { function search() { - throw new Error("search error"); + throw new Error("erro de pesquisa"); } return ( There was an error while submitting the form

} + fallback={

Ocorreu um erro ao enviar o formulário

} > - +
); @@ -318,15 +317,15 @@ export default function Search() {
-### Display a form submission error without JavaScript {/*display-a-form-submission-error-without-javascript*/} +### Exibir um erro de envio do formulário sem JavaScript {/*display-a-form-submission-error-without-javascript*/} -Displaying a form submission error message before the JavaScript bundle loads for progressive enhancement requires that: +Exibir uma mensagem de erro de envio do formulário antes que o pacote JavaScript carregue para aprimoramento progressivo requer que: -1. `
` be rendered by a [Server Component](/reference/rsc/use-client) -1. the function passed to the ``'s `action` prop be a [Server Action](/reference/rsc/use-server) -1. the `useActionState` Hook be used to display the error message +1. `` seja renderizado por um [Componente do Servidor](/reference/rsc/use-client) +1. a função passada para a prop `action` do `` seja uma [Ação do Servidor](/reference/rsc/use-server) +1. o Hook `useActionState` seja usado para exibir a mensagem de erro -`useActionState` takes two parameters: a [Server Action](/reference/rsc/use-server) and an initial state. `useActionState` returns two values, a state variable and an action. The action returned by `useActionState` should be passed to the `action` prop of the form. The state variable returned by `useActionState` can be used to displayed an error message. The value returned by the [Server Action](/reference/rsc/use-server) passed to `useActionState` will be used to update the state variable. +`useActionState` aceita dois parâmetros: uma [Ação do Servidor](/reference/rsc/use-server) e um estado inicial. `useActionState` retorna dois valores, uma variável de estado e uma ação. A ação retornada pelo `useActionState` deve ser passada para a prop `action` do formulário. A variável de estado retornada pelo `useActionState` pode ser usada para exibir uma mensagem de erro. O valor retornado pela [Ação do Servidor](/reference/rsc/use-server) passada para `useActionState` será usado para atualizar a variável de estado. @@ -340,7 +339,7 @@ export default function Page() { const email = formData.get("email"); try { await signUpNewUser(email); - alert(`Added "${email}"`); + alert(`Adicionado "${email}"`); } catch (err) { return err.toString(); } @@ -348,12 +347,12 @@ export default function Page() { const [message, signupAction] = useActionState(signup, null); return ( <> -

Signup for my newsletter

-

Signup with the same email twice to see an error

+

Inscreva-se para minha newsletter

+

Inscreva-se com o mesmo email duas vezes para ver um erro

- + {!!message &&

{message}

} @@ -366,7 +365,7 @@ let emails = []; export async function signUpNewUser(newEmail) { if (emails.includes(newEmail)) { - throw new Error("This email address has already been added"); + throw new Error("Este endereço de email já foi adicionado"); } emails.push(newEmail); } @@ -386,13 +385,13 @@ export async function signUpNewUser(newEmail) {
-Learn more about updating state from a form action with the [`useActionState`](/reference/react/useActionState) docs +Saiba mais sobre atualizar o estado a partir de uma ação de formulário com a documentação do [`useActionState`](/reference/react/useActionState) -### Handling multiple submission types {/*handling-multiple-submission-types*/} +### Tratando múltiplos tipos de envio {/*handling-multiple-submission-types*/} -Forms can be designed to handle multiple submission actions based on the button pressed by the user. Each button inside a form can be associated with a distinct action or behavior by setting the `formAction` prop. +Os formulários podem ser projetados para lidar com várias ações de envio, com base no botão pressionado pelo usuário. Cada botão dentro de um formulário pode ser associado a uma ação ou comportamento distinto definindo a prop `formAction`. -When a user taps a specific button, the form is submitted, and a corresponding action, defined by that button's attributes and action, is executed. For instance, a form might submit an article for review by default but have a separate button with `formAction` set to save the article as a draft. +Quando um usuário clica em um botão específico, o formulário é enviado, e uma ação correspondente, definida pelos atributos e ação daquele botão, é executada. Por exemplo, um formulário pode enviar um artigo para revisão por padrão, mas ter um botão separado com `formAction` definido para salvar o artigo como um rascunho. @@ -401,20 +400,20 @@ export default function Search() { function publish(formData) { const content = formData.get("content"); const button = formData.get("button"); - alert(`'${content}' was published with the '${button}' button`); + alert(`'${content}' foi publicado com o botão '${button}'`); } function save(formData) { const content = formData.get("content"); - alert(`Your draft of '${content}' has been saved!`); + alert(`Seu rascunho de '${content}' foi salvo!`); } return (