@@ -489,97 +480,92 @@ function ApiPage({
{`Record`} = {`{}`}
+
+ Video
+
-
{api.useForm.defaultValues(goToSection)}
- // ✅ working version
- register({ name: 'lastName' })} />
-// ❌ above example does not work with "defaultValues" due to its "ref" not being provided
-`}
- tsRawData={`type Inputs = {
- firstName: string;
- lastName: string;
- email: string;
- pets: string[];
-}
-
-const { register } = useForm({
- defaultValues: {
- firstName: "bill",
- lastName: "luo",
- email: "bluebill1049@hotmail.com",
- pets: [ 'dog', 'cat' ]
- }
-})
+
- // ✅ working version
- register({ name: 'lastName' })} />
-// ❌ above example does not work with "defaultValues" due to its "ref" not being provided
-`}
- />
+
+ Note:{" "}
+ isValid is affected by{" "}
+ goToSection("useForm", sectionsRef)}
+ >
+ mode
+
+ . This state is only applicable with onChange{" "}
+ and onBlur mode.
+
+
+
+
+
+
+
+ >
+ )
+ }
+)
diff --git a/src/components/V5/ApiPageV5.tsx b/src/components/V5/ApiPageV5.tsx
new file mode 100644
index 000000000..9a2e70076
--- /dev/null
+++ b/src/components/V5/ApiPageV5.tsx
@@ -0,0 +1,1064 @@
+import * as React from "react"
+import ApiRefTable from "../ApiRefTable"
+import validationSchemaCode from "../V5/codeExamples/validationSchema"
+import validationSchemaNative from "../V5/codeExamples/validationSchemaNative"
+import CodeArea, { CodeSandBoxLink } from "../CodeArea"
+import SideMenu from "../SideMenu"
+import ApiFormState from "./ApiFormStateV5"
+import resetCode from "../V5/codeExamples/resetCode"
+import ApiWatch from "./ApiWatchV5"
+import ApiErrors from "./ApiErrorsV5"
+import handleSubmitCode from "../V5/codeExamples/handleSubmitCode"
+import setError from "../V5/codeExamples/setError"
+import clearError from "../V5/codeExamples/clearError"
+import setValue from "../V5/codeExamples/setValue"
+import setValueTs from "../V5/codeExamples/setValueTs"
+import getValues from "../V5/codeExamples/getValues"
+import getValuesTs from "../V5/codeExamples/getValuesTs"
+import defaultValues from "./codeExamples/defaultExample"
+import defaultValuesTs from "./codeExamples/defaultExampleTs"
+import trigger from "../V5/codeExamples/trigger"
+import Footer from "../Footer"
+import FormContext from "../FormContext"
+import unregisterCode from "../V5/codeExamples/unregisterCode"
+import unregisterCodeTs from "../V5/codeExamples/unregisterCodeTs"
+import Popup from "../Popup"
+import { navigate } from "@reach/router"
+import { useStateMachine } from "little-state-machine"
+import generic from "../../data/generic"
+import apiEn from "../../data/V5/en/api"
+import Controller from "../Controller"
+import ErrorMessage from "./ErrorMessageV5"
+import translateLink from "../logic/translateLink"
+import TabGroup from "../TabGroup"
+import setMultipleErrors from "../V5/codeExamples/setMultipleErrors"
+import setAllErrors from "../V5/codeExamples/setAllErrors"
+import resetCodeControlled from "../V5/codeExamples/resetCodeControlled"
+import resetController from "../V5/codeExamples/resetController"
+import resetControllerTs from "../V5/codeExamples/resetControllerTs"
+import control from "../V5/codeExamples/control"
+import nativeValidation from "../V5/codeExamples/nativeValidation"
+import UseFieldArray from "../UseFieldArray"
+import colors from "../../styles/colors"
+import ValidationResolver from "./ValidationResolverV5"
+import headerStyles from "../Header.module.css"
+import typographyStyles from "../../styles/typography.module.css"
+import tableStyles from "../../styles/table.module.css"
+import buttonStyles from "../../styles/button.module.css"
+import containerStyles from "../../styles/container.module.css"
+import styles from "../ApiPage.module.css"
+
+const { useRef, useEffect } = React
+
+const enLinks = [
+ apiEn.useForm,
+ apiEn.register,
+ apiEn.unregister,
+ apiEn.errors,
+ apiEn.watch,
+ apiEn.handleSubmit,
+ apiEn.reset,
+ apiEn.setError,
+ apiEn.clearError,
+ apiEn.setValue,
+ apiEn.getValues,
+ apiEn.triggerValidation,
+ apiEn.control,
+ apiEn.formState,
+ apiEn.Controller,
+ apiEn.ErrorMessage,
+ apiEn.useFormContext,
+ apiEn.useFieldArray,
+ apiEn.validationResolver,
+ apiEn.validationSchema,
+ apiEn.NativeValidation,
+]
+
+const codeSandBoxStyle = {
+ position: "relative",
+ left: 0,
+ float: "right",
+}
+
+interface Props {
+ formData?: any
+ defaultLang: string
+ api: any
+}
+
+function ApiPage({ formData, defaultLang, api }: Props) {
+ const {
+ state,
+ state: { language },
+ } = useStateMachine()
+ const lightMode = state?.setting?.lightMode
+ const isUnmount = useRef(false)
+ const { currentLanguage } =
+ language && language.currentLanguage
+ ? language
+ : { currentLanguage: defaultLang }
+ const [activeIndex, setActiveIndex] = React.useState(0)
+ const links = [
+ api.useForm,
+ api.register,
+ api.unregister,
+ api.errors,
+ api.watch,
+ api.handleSubmit,
+ api.reset,
+ api.setError,
+ api.clearError,
+ api.setValue,
+ api.getValues,
+ api.triggerValidation,
+ api.control,
+ api.formState,
+ api.Controller,
+ api.ErrorMessage,
+ api.useFormContext,
+ api.useFieldArray,
+ api.validationResolver,
+ api.validationSchema,
+ api.NativeValidation,
+ ]
+ const copyFormData = useRef([])
+ const apiSectionsRef = useRef({
+ useFormRef: null,
+ registerRef: null,
+ unregisterRef: null,
+ errorsRef: null,
+ watchRef: null,
+ handleSubmitRef: null,
+ resetRef: null,
+ setErrorRef: null,
+ clearErrorRef: null,
+ setValueRef: null,
+ getValuesRef: null,
+ triggerValidationRef: null,
+ controlRef: null,
+ formStateRef: null,
+ ControllerRef: null,
+ ErrorMessageRef: null,
+ useFormContextRef: null,
+ useFieldArrayRef: null,
+ validationResolverRef: null,
+ validationSchemaRef: null,
+ BrowserbuiltinvalidationRef: null,
+ })
+ copyFormData.current = formData
+
+ const goToSection = (name, animate = true) => {
+ const url = window.location.href
+ const hashIndex = url.indexOf("#")
+ const filterName = name.replace(/ |-/g, "")
+
+ history.pushState(
+ {},
+ null,
+ hashIndex < 0
+ ? `${url}#${filterName}`
+ : `${url.substr(0, hashIndex)}#${filterName}`
+ )
+
+ const refName = `${filterName}Ref`
+
+ if (apiSectionsRef.current[refName]) {
+ apiSectionsRef.current[refName].scrollIntoView(
+ animate &&
+ Math.abs(
+ Object.keys(apiSectionsRef.current).findIndex(
+ (item) => item === refName
+ ) - activeIndex
+ ) < 5
+ ? { behavior: "smooth" }
+ : undefined
+ )
+ }
+ }
+
+ useEffect(() => {
+ if (location.hash) {
+ setTimeout(() => goToSection(location.hash.substr(1), false), 10)
+ }
+ }, [])
+
+ useEffect(() => {
+ if (isUnmount.current) return
+ try {
+ const observer = new IntersectionObserver(
+ (entries) => {
+ let index = 0
+ const allTops = []
+ for (const entrie of entries) {
+ try {
+ for (const key in apiSectionsRef.current) {
+ const { top } = apiSectionsRef.current[
+ key
+ ].getBoundingClientRect()
+ allTops.push(top)
+ index++
+ }
+ } catch {}
+ }
+
+ index = 0
+ let foundIndex = 0
+ let temp
+
+ for (const top of allTops) {
+ if (temp === undefined || Math.abs(top) < Math.abs(temp)) {
+ temp = top
+ foundIndex = index
+ }
+ index++
+ }
+
+ setActiveIndex(foundIndex)
+ },
+ {
+ rootMargin: "100px",
+ threshold: [0.01],
+ }
+ )
+
+ Object.values(apiSectionsRef.current).forEach((item) => {
+ if (item) {
+ observer.observe(item)
+ }
+ })
+ } catch {}
+
+ return () => {
+ isUnmount.current = true
+ }
+ }, [])
+
+ return (
+
console.log(data))}>
+ {* // Preferred syntax on most cases. If you need props, pass TextField props to Controller props (forwarded) *}
+
+
+ {* // Another approach is using render props to customise event and value *}
+ (
+
+ )}
+ />
+
+
+
- This is a{" "}
-
- render prop
- {" "}
- for rendering error message or messages.
-
- Note: you need to set{" "}
- validateCriteriaMode to 'all' for using messages.
-
-
-
-
- ),
+ table: {
+ name: <>associated field name.>,
+ errors: (
+ <>
+ errors object from React Hook Form. It's optional if you
+ are using FormContext.
+ >
+ ),
+ message: <>inline error message.>,
+ as: (
+ <>
+ Wrapper component or HTML tag. eg: as="span" or{" "}
+ {`as={}`}
+ >
+ ),
+ children: (
+ <>
+ This is a{" "}
+
+ render prop
+ {" "}
+ for rendering error message or messages.
+
+ Note: you need to set{" "}
+ validateCriteriaMode to 'all' for using messages.
+
+ >
+ ),
+ },
},
NativeValidation: {
title: "Browser built-in validation",
diff --git a/src/data/es/api-v5.tsx b/src/data/V5/es/api.tsx
similarity index 91%
rename from src/data/es/api-v5.tsx
rename to src/data/V5/es/api.tsx
index c921f24df..59e4387fe 100644
--- a/src/data/es/api-v5.tsx
+++ b/src/data/V5/es/api.tsx
@@ -1,19 +1,26 @@
import * as React from "react"
import { Link as NavLink } from "gatsby"
-import colors from "../../styles/colors"
-import translateLink from "../../components/logic/translateLink"
-import Popup from "../../components/Popup"
-import CodeArea from "../../components/CodeArea"
-import useFieldArrayArgument from "../../components/codeExamples/useFieldArrayArgument"
-import typographyStyles from "../../styles/typography.module.css"
-import buttonStyles from "../../styles/button.module.css"
-import code from "../../components/codeExamples/defaultExample"
+import colors from "../../../styles/colors"
+import translateLink from "../../../components/logic/translateLink"
+import Popup from "../../../components/Popup"
+import CodeArea from "../../../components/CodeArea"
+import useFieldArrayArgument from "../../../components/codeExamples/useFieldArrayArgument"
+import typographyStyles from "../../../styles/typography.module.css"
+import buttonStyles from "../../../styles/button.module.css"
+import code from "../../../components/codeExamples/defaultExample"
export default {
title: "Documentación de la API",
header: {
description: "se enfoca en proveer la mejor DX simplificando la API.",
},
+ v5upgradeAlert: (
+
+ ► Se libera React Hook Form V6. Si
+ planea actualizar, lea la{" "}
+ Guía de migración a V6.
+
- Aplica reglas de validación de formularios con Yup
+ Aplica reglas de validación de formularios con Yup
en el nivel de esquema, por favor refiérase a la sección{" "}
+
+
+ Nota:múltiples radio input
+ con el mismo nombre, desea registrar la validación hasta el último
+ input para que el hook entienda validarlos como un grupo al final.
+
>
),
},
@@ -409,6 +428,18 @@ export default {
),
message: `Message es un string vacio por defecto. Sin embargo, si registra la validación con un mensaje de error, se devolverá.`,
ref: `Referencia del input.`,
+ note: (goToSection) => (
+
+ Nota: puede usar{" "}
+ goToSection("ErrorMessage")}
+ >
+ ErrorMessage
+ {" "}
+ para ayudar a manejar sus estados de erro
+
- (args: any | EventTarget) => any
+ (args: any | EventTarget) => any
@@ -761,11 +792,6 @@ export default {
Esta propiedad onChange te permitirá customizar el
valor de retorno, asegúrese de conocer la forma de los accesorios
del componente externo value.
- event.target.value}}
-onChange={{([ event, data ]) => ({ checked: data.checked})}}`}
- />
@@ -867,7 +893,7 @@ onChange={{([ event, data ]) => ({ checked: data.checked})}}`}
Form context está destinado a resolver el problema cuando hay inputs
anidados profundamente en el árbol de componentes y pasar métodos hasta
el fondo como {""}
- propiedades se vuelve tedioso.
+ propiedadesse vuelve tedioso.
),
description: (
@@ -903,83 +929,38 @@ onChange={{([ event, data ]) => ({ checked: data.checked})}}`}
asociado.
),
- table: (
-
-
-
- name
-
-
- string
-
-
✓
-
Nombre de campo asociado.
-
-
-
- errors
-
-
- object
-
-
✓
-
- Objeto errors de React Hook Form
-
-
-
-
- message
-
-
- string
-
-
-
mensaje de error en línea.
-
-
-
- as
-
-
-
- React.ElementType | string
-
-
-
-
- Componente wrappeado o un tag HTML. ej: as="span" o{" "}
- {`as={}`}
-
Importante: debido a que
las entradas pueden ser no-controladas, se requiere{" "}
- id con componentes mapeados para ayudar a React a
+ idcon componentes mapeados para ayudar a React a
identificar qué elementos se han cambiado, agregado o eliminado.
Inserta input/inputs en una posición en particular.
@@ -1157,7 +1138,7 @@ React.useEffect(() => {
- (from: number, to: number) => void
+ (from: number, to: number) => void
Intercambia las posiciones de los input/inputs.
@@ -1168,7 +1149,7 @@ React.useEffect(() => {
- (from: number, to: number) => void
+ (from: number, to: number) => void
@@ -1188,7 +1169,7 @@ React.useEffect(() => {
- (index?: number | number[]) => void
+ (index?: number | number[]) => void
@@ -1232,7 +1213,7 @@ React.useEffect(() => {
Nota: asegúrate de que eres
devolver objeto que contiene values y errors
, y su valor predeterminado debe ser un objeto vacío{" "}
- {`{}`} .
+ {`{}`}.
diff --git a/src/data/jp/api-v5.tsx b/src/data/V5/jp/api.tsx
similarity index 93%
rename from src/data/jp/api-v5.tsx
rename to src/data/V5/jp/api.tsx
index 2bf66ab97..f404b4bdc 100644
--- a/src/data/jp/api-v5.tsx
+++ b/src/data/V5/jp/api.tsx
@@ -1,12 +1,13 @@
import * as React from "react"
-import colors from "../../styles/colors"
-import Popup from "../../components/Popup"
-import generic from "../generic"
-import CodeArea from "../../components/CodeArea"
-import useFieldArrayArgument from "../../components/codeExamples/useFieldArrayArgument"
-import typographyStyles from "../../styles/typography.module.css"
-import buttonStyles from "../../styles/button.module.css"
-import code from "../../components/codeExamples/defaultExample"
+import { Link } from "gatsby"
+import colors from "../../../styles/colors"
+import Popup from "../../../components/Popup"
+import generic from "../../generic"
+import CodeArea from "../../../components/CodeArea"
+import useFieldArrayArgument from "../../../components/codeExamples/useFieldArrayArgument"
+import typographyStyles from "../../../styles/typography.module.css"
+import buttonStyles from "../../../styles/button.module.css"
+import code from "../../../components/codeExamples/defaultExample"
export default {
title: "API ドキュメント",
@@ -14,6 +15,13 @@ export default {
description:
"は API をシンプルにすることにより、最高な DX を提供することに焦点を当てています。",
},
+ v5upgradeAlert: (
+
+ Nota: multiple radio inputs
+ with the same name, you want to register the validation to the last
+ input so the hook understand validate them as a group at the end.
+
- (from: number, to: number) => void
+ (from: number, to: number) => void
input の位置を入れ替えます。
@@ -1210,7 +1197,7 @@ React.useEffect(() => {
- (from: number, to: number) => void
+ (from: number, to: number) => void
@@ -1230,7 +1217,7 @@ React.useEffect(() => {
- (index?: number | number[]) => void
+ (index?: number | number[]) => void
diff --git a/src/data/kr/api-v5.tsx b/src/data/V5/kr/api.tsx
similarity index 91%
rename from src/data/kr/api-v5.tsx
rename to src/data/V5/kr/api.tsx
index 466434b46..ec627b996 100644
--- a/src/data/kr/api-v5.tsx
+++ b/src/data/V5/kr/api.tsx
@@ -1,18 +1,28 @@
import * as React from "react"
-import colors from "../../styles/colors"
-import Popup from "../../components/Popup"
-import generic from "../generic"
-import CodeArea from "../../components/CodeArea"
-import useFieldArrayArgument from "../../components/codeExamples/useFieldArrayArgument"
-import typographyStyles from "../../styles/typography.module.css"
-import buttonStyles from "../../styles/button.module.css"
-import code from "../../components/codeExamples/defaultExample"
+import { Link } from "gatsby"
+import colors from "../../../styles/colors"
+import Popup from "../../../components/Popup"
+import generic from "../../generic"
+import CodeArea from "../../../components/CodeArea"
+import useFieldArrayArgument from "../../../components/codeExamples/useFieldArrayArgument"
+import typographyStyles from "../../../styles/typography.module.css"
+import buttonStyles from "../../../styles/button.module.css"
+import code from "../../../components/codeExamples/defaultExample"
export default {
title: "API 설명서",
header: {
- description: "은 API 단순화를 통해 최고의 DX를 제공합니다.",
+ description:
+ "단순화된 API 를 통해 최고의 DX 를 제공하는데 초점을 맞추었습니다.",
},
+ v5upgradeAlert: (
+
+ ► 리 액트 훅 폼 V6이 출시되었습니다.
+ 업그레이드를 계획하고 있다면{" "}
+ V6으로의 마이그레이션 안내서 을
+ 읽어보십시오.
+
+ ),
useForm: {
title: "useForm",
intro: (
@@ -303,6 +313,18 @@ export default {
동안 커스텀 등록된 입력을 다시 렌더링 하도록 하려면, 등록된 입력의
타입을 지정해 주어야 합니다.
+
+
+ Nota: multiple radio inputs
+ with the same name, you want to register the validation to the last
+ input so the hook understand validate them as a group at the end.
+
>
),
},
@@ -402,6 +424,18 @@ export default {
),
message: `메시지는 기본적으로 빈 문자열입니다. 하지만 에러 메시지와 함께 유효성 검사를 함께 등록하면, 이 값이 반환됩니다.`,
ref: `입력 엘레먼트에 대한 ref`,
+ note: (goToSection) => (
+
+ 참고: {" "}
+ goToSection("ErrorMessage")}
+ >
+ ErrorMessage
+ {" "}
+ 를 사용하여 오류 상태를 처리 할 수 있습니다.
+
이 함수는 폼 내의 필드 값과 에러를 재설정(reset) 합니다.{" "}
- omitResetState 를 제공하면 자유롭게 특정 상태 만
+ omitResetState를 제공하면 자유롭게 특정 상태 만
재설정합니다. values를 옵셔널 인수로 전달하면 폼의 기본
값으로 재설정 할 수 있습니다.
- (from: number, to: number) => void
+ (from: number, to: number) => void
입력 필드(들)의 위치를 서로 교체합니다.
@@ -1160,7 +1149,7 @@ React.useEffect(() => {
- (from: number, to: number) => void
+ (from: number, to: number) => void
@@ -1180,7 +1169,7 @@ React.useEffect(() => {
- (index?: number | number[]) => void
+ (index?: number | number[]) => void
diff --git a/src/data/pt/api-v5.tsx b/src/data/V5/pt/api.tsx
similarity index 91%
rename from src/data/pt/api-v5.tsx
rename to src/data/V5/pt/api.tsx
index bce88e4e0..dc0eda7d6 100644
--- a/src/data/pt/api-v5.tsx
+++ b/src/data/V5/pt/api.tsx
@@ -1,12 +1,13 @@
import * as React from "react"
-import colors from "../../styles/colors"
-import Popup from "../../components/Popup"
-import generic from "../generic"
-import CodeArea from "../../components/CodeArea"
-import useFieldArrayArgument from "../../components/codeExamples/useFieldArrayArgument"
-import typographyStyles from "../../styles/typography.module.css"
-import buttonStyles from "../../styles/button.module.css"
-import code from "../../components/codeExamples/defaultExample"
+import { Link } from "gatsby"
+import colors from "../../../styles/colors"
+import Popup from "../../../components/Popup"
+import generic from "../../generic"
+import CodeArea from "../../../components/CodeArea"
+import useFieldArrayArgument from "../../../components/codeExamples/useFieldArrayArgument"
+import typographyStyles from "../../../styles/typography.module.css"
+import buttonStyles from "../../../styles/button.module.css"
+import code from "../../../components/codeExamples/defaultExample"
export default {
title: "API Documentação",
@@ -14,6 +15,13 @@ export default {
description:
"foca em prover a melhor experiência para o desenvolvedor com uma API Simplificada",
},
+ v5upgradeAlert: (
+
+ ► O formulário de gancho de reação
+ V6 é liberado. Se você está planejando atualizar, leia o{" "}
+ Guia de migração para V6.
+
+ ),
useForm: {
title: "useForm",
intro: (
@@ -312,6 +320,19 @@ export default {
registro de campo customizado para ativar a re-renderização seu
valor, então você precisa dar um tempo ao seu campo{" "}
+
+
+ Nota:
+ várias raido input com o mesmo nome, você deseja registrar a
+ validação até o último entrada para que o gancho entenda valide-os
+ como um grupo no final.
+
>
),
},
@@ -419,6 +440,18 @@ export default {
),
message: `'Message' é um campo string e vazio por padrão. Entretanto, se você registrar a validação com mensagem de erro, ele será retornado.`,
ref: `Referência para o elemento do campo.`,
+ note: (goToSection) => (
+
+ Nota: você pode usar o{" "}
+ goToSection("ErrorMessage")}
+ >
+ ErrorMessage
+ {" "}
+ para ajudar a lidar com seus estados de erro.
+
Essa função irá limpar o valor dos campos, e erros dentro do
- formulário. Ao fornecer omitResetState , você tem a
+ formulário. Ao fornecer omitResetState , você tem a
liberdade de redefina apenas parte específica do estado. Você pode
passar values como valor opcional para resetar o
formulário assinado com o valor padrão.
@@ -526,9 +559,9 @@ export default {
Nota: Você vai precisar
- fornecer defaultValues durante useForm
- ou reset com valor para redefinir no
- Controller o valor dos componentes.
+ fornecer defaultValues durante useForm
+ ouresetcom valor para redefinir no
+ Controller o valor dos componentes.
>
),
@@ -737,9 +770,9 @@ export default {
Note: se o seu formulário
- invocar reset com valores diferentes, você
- precisará fornecer defaultValues no nível useForm em
- vez de definido inline defaultValue..
+ invocar resetcom valores diferentes, você precisará
+ fornecer defaultValues no nível useForm em vez de
+ definido inline defaultValue..
@@ -761,7 +794,7 @@ export default {
- (args: any | EventTarget) => any
+ (args: any | EventTarget) => any
@@ -769,11 +802,6 @@ export default {
A propriedade onChange lhe permite customizar o retorno
do valor, verifique se o formato do componente externo{" "}
value props.
- event.target.value}}
-onChange={{([ event, data ]) => ({ checked: data.checked})}}`}
- />
- (from: number, to: number) => void
+ (from: number, to: number) => void
Swap input/inputs posição.
@@ -1197,7 +1180,7 @@ React.useEffect(() => {
- (from: number, to: number) => void
+ (from: number, to: number) => void
@@ -1216,7 +1199,7 @@ React.useEffect(() => {
- (index?: number | number[]) => void
+ (index?: number | number[]) => void
diff --git a/src/data/ru/api-v5.tsx b/src/data/V5/ru/api.tsx
similarity index 92%
rename from src/data/ru/api-v5.tsx
rename to src/data/V5/ru/api.tsx
index ee5bc1bdf..b7983d12b 100644
--- a/src/data/ru/api-v5.tsx
+++ b/src/data/V5/ru/api.tsx
@@ -1,11 +1,12 @@
import * as React from "react"
-import colors from "../../styles/colors"
-import Popup from "../../components/Popup"
-import CodeArea from "../../components/CodeArea"
-import useFieldArrayArgument from "../../components/codeExamples/useFieldArrayArgument"
-import typographyStyles from "../../styles/typography.module.css"
-import buttonStyles from "../../styles/button.module.css"
-import code from "../../components/codeExamples/defaultExample"
+import { Link } from "gatsby"
+import colors from "../../../styles/colors"
+import Popup from "../../../components/Popup"
+import CodeArea from "../../../components/CodeArea"
+import useFieldArrayArgument from "../../../components/codeExamples/useFieldArrayArgument"
+import typographyStyles from "../../../styles/typography.module.css"
+import buttonStyles from "../../../styles/button.module.css"
+import code from "../../../components/codeExamples/defaultExample"
export default {
title: "Документация по API",
@@ -13,6 +14,13 @@ export default {
description:
"сфокусирован на предоставлении лучшего опыта разработки за счет упрощения API.",
},
+ v5upgradeAlert: (
+
+ ► React Hook Form V6 выпущен. Если
+ вы планируете выполнить обновление, ознакомьтесь с{" "}
+ Руководство по миграции на V6.
+
+ ),
useForm: {
title: "useForm",
intro: (
@@ -315,6 +323,18 @@ export default {
обновления его значения, то вам нужно указать тип
зарегистрированного поля.
+
+
+ Nota:несколько radio input
+ с тем же именем, вы хотите зарегистрировать валидацию до последнего
+ ввод, чтобы ловушка понимала, валидируйте их как группу в конце.
+
>
),
},
@@ -420,6 +440,19 @@ export default {
),
message: `Сообщение является пустой строкой по умолчанию. Однако, если вы зарегистрируете валидацию с сообщением об ошибке, то затем она будет возвращена.`,
ref: `Ссылка на ваш элемент поля.`,
+ note: (goToSection) => (
+
+ Примечание: вы можете
+ использовать{" "}
+ goToSection("ErrorMessage")}
+ >
+ ErrorMessage
+ {" "}
+ чтобы помочь обработать ваши ошибки.
+
Эта функция сбрасывает значения полей и ошибки формы. Поставив{" "}
- omitResetState , вы можете свободно только сбросить
+ omitResetState , вы можете свободно только сбросить
конкретный кусок состояния. Вы можете передать values в
качестве необязательного аргумента для сброса формы в присвоенные
значения по умолчанию.
@@ -527,9 +560,9 @@ export default {
Примечание: Вам нужно будет
- укажите defaultValues во время useForm
- или reset со значением для сброса
- Controller стоимость компонентов.
+ укажите defaultValues во время useForm
+ илиresetсо значением для сброса
+ Controller стоимость компонентов.
- (from: number, to: number) => void
+ (from: number, to: number) => void
@@ -852,7 +885,7 @@ React.useEffect(() => {
- (from: number, to: number) => void
+ (from: number, to: number) => void
@@ -873,7 +906,7 @@ React.useEffect(() => {
- (index?: number | number[]) => void
+ (index?: number | number[]) => void
@@ -970,7 +1003,7 @@ React.useEffect(() => {
- (args: any | EventTarget) => any
+ (args: any | EventTarget) => any
@@ -981,11 +1014,6 @@ React.useEffect(() => {
или checked будет считываться, когда форма полезных
данных представляет собой object, который содержит
атрибут type.
- event.target.value}}
-onChange={{([ event, data ]) => ({ checked: data.checked})}}`}
- />
>
),
},
@@ -332,7 +351,7 @@ export default {
一起包装以提高渲染性能,因此请使您在渲染前先调用/读取它,以启用状态更新。
这个减少重新渲染功能功能由于缺少而仅适用于Web平台React Native上的
- Proxy 支持。
+ Proxy 支持。
>
),
@@ -401,12 +420,23 @@ export default {
<>
This is useful for input validation like rules of password, which
multiple errors need to return for a single field. To enable this
- feature, make sure you have set validateCriteriaMode: 'all'
- .
+ feature, make sure you have set criteriaMode 'all'.
>
),
message: `默认情况下消息是空字符串。 但是,如果您使用错误消息注册验证,那么它将被返回。`,
ref: `输入元素的参考。`,
+ note: (goToSection) => (
+
- (from: number, to: number) => void
+ (from: number, to: number) => void
@@ -1135,7 +1114,7 @@ React.useEffect(() => {
- (from: number, to: number) => void
+ (from: number, to: number) => void
@@ -1156,7 +1135,7 @@ React.useEffect(() => {
- (index?: number | number[]) => void
+ (index?: number | number[]) => void
diff --git a/src/data/advanced.tsx b/src/data/advanced.tsx
deleted file mode 100644
index c89d9a906..000000000
--- a/src/data/advanced.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-import advancedEn from "../data/en/advanced"
-import advancedEs from "../data/es/advanced"
-import advancedPt from "../data/pt/advanced"
-import advancedZh from "../data/zh/advanced"
-import advancedJp from "../data/jp/advanced"
-import advancedKr from "../data/kr/advanced"
-import advancedRu from "../data/ru/advanced"
-
-export default {
- en: advancedEn,
- es: advancedEs,
- pt: advancedPt,
- kr: advancedKr,
- jp: advancedJp,
- zh: advancedZh,
- ru: advancedRu,
-}
diff --git a/src/data/api.tsx b/src/data/api.tsx
deleted file mode 100644
index 12207d046..000000000
--- a/src/data/api.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-import apiEn from "../data/en/api"
-import apiEs from "../data/es/api"
-import apiPt from "../data/pt/api"
-import apiZh from "../data/zh/api"
-import apiJp from "../data/jp/api"
-import apiKr from "../data/kr/api"
-import apiRu from "../data/ru/api"
-
-export default {
- en: apiEn,
- es: apiEs,
- pt: apiPt,
- kr: apiKr,
- jp: apiJp,
- zh: apiZh,
- ru: apiRu,
-}
diff --git a/src/data/en/advanced.tsx b/src/data/en/advanced.tsx
index b1d19d575..bd32f6807 100644
--- a/src/data/en/advanced.tsx
+++ b/src/data/en/advanced.tsx
@@ -4,6 +4,7 @@ import accessibleCodeBase from "../../components/codeExamples/accessibleCodeBase
import accessibleCodeFinal from "../../components/codeExamples/accessibleCodeFinal"
import customHookWithValidationResolver from "../../components/codeExamples/customHookWithValidationResolver"
import { step1, step2, step3 } from "../../components/codeExamples/formWizard"
+import * as CodeExampleTestingForm from "../../components/codeExamples/testingForm"
import smartForm from "../../components/codeExamples/smartForm"
import form from "../../components/codeExamples/form"
import input from "../../components/codeExamples/input"
@@ -185,8 +186,8 @@ export default {
Step 2: Create your pages,
- collect and submit the data to the store and show the next page of
- your form.
+ collect and submit the data to the store and push to the next
+ form/page.
Let's have a look what's in each of those components.
-
+
Form
-
+
The Form component's responsibility is to inject all{" "}
@@ -243,9 +244,9 @@ export default {
url="https://codesandbox.io/s/react-hook-form-smart-form-component-eqb3n"
/>
-
+
Input / Select
-
+
Those input components' responsibility is to registering them into{" "}
@@ -300,54 +301,23 @@ export default {
>
link for such implementation.
{" "}
- with Controller.
+ with Controller.
- React Hook Form supports schema-based form validation with{" "}
-
- Yup
-
- , where you can pass your validationSchema to{" "}
- useForm as an optional config. React Hook
- Form will validate your input data against the schema and return with
- either errors or a valid result.
-
- >
- ),
- step1: (
- <>
-
- Step 1: Install{" "}
- Yup into your project.
-
- >
- ),
- step2: (
-
- Step 2: Prepare your schema for
- validation and register inputs with React Hook Form.
-
When we are building forms, there are times when our input lives inside
of deeply nested component trees, and that's when{" "}
- FormContext comes in very handy.
- However, we can further improve the Developer Experience by creating a{" "}
+ FormContext comes in handy. However,
+ we can further improve the Developer Experience by creating a{" "}
ConnectForm component and leveraging React's{" "}
renderProps.
- The benefit of such a component is you can connect your input with React
- Hook Form from anywhere.
+ The benefit is you can connect your input with React Hook Form from much
+ easier.
),
},
@@ -372,10 +342,10 @@ export default {
-
- Import Controller to
- wrap your component and let it manage register and unregister
-
+
Toggle the input's viability
+
+
+
Building separate form for modal and pop up form
@@ -392,6 +362,12 @@ export default {
with custom register
+
+
+ Import Controller to
+ wrap your component and let it manage register and unregister
+
- You can build a custom hook as a validation resolver. A custom hook
- can easily integrate with yup/Joi/Superstruct as a validation method,
- and to be used inside validation resolver.
+ You can build a custom hook as a resolver. A custom hook can easily
+ integrate with yup/Joi/Superstruct as a validation method, and to be
+ used inside validation resolver.
- Define a memoized validation schema (or define it outside your
- component if you don't have any dependencies)
+
+ Define a memoized validation schema (or define it outside your
+ component if you don't have any dependencies)
+
+
+
+
Use the custom hook, by passing the validation schema
+
+
+
Pass the validation resolver to the useForm hook
-
Use the custom hook, by passing the validation schema
-
Pass the validation resolver to the useForm hook
@@ -455,7 +437,7 @@ export default {
To work around this, you can manually register the fields, and then
- programatically set the value of the field.
+ programmatically set the value of the field.
+ Testing is very important because it preserve code from bugs or
+ mistakes and guarantee code safety when you refactor the codebase.
+
+
+
+ We recommend using{" "}
+
+ testing-library
+
+ , because it is simple and tests are more focused on user behavior.
+
+
+
♦
+
+
+ Step 1: Set up your testing
+ environment.
+
+
+
+ Please install{" "}
+
+ @testing-library/jest-dom
+ {" "}
+ with the latest version of jest because react-hook-form
+ use MutationObserver to detect inputs get unmounted from
+ the DOM.
+
+ Finally, you have to update setup.js in{" "}
+ jest.config.js to include the file.
+
+
+
+
+
+ Step 2: Create login form.
+
+
+
+ We have set the role attribute accordingly. These attributes are
+ helpful when you will write tests and improve accessibility. For more
+ information, you can refer to the{" "}
+
+ testing-library
+ {" "}
+ documentation.
+
+
+
+
+
+ Step 3: Write tests.
+
+
+
The following criteria are what we try to cover with the tests:
+
+
+
+
Test submission failure.
+
+
+ We are using waitFor and find* method to
+ detect submission feedback because handleSubmit{" "}
+ method is executed asynchronously.
+
+
+
+
Test validation associated with each inputs.
+
+
+ We are using *ByRole method when querying different
+ elements because that's how users recognize your UI component.
+
+
+
+
Test successful submission.
+
+
+
+
+ >
+ ),
+ },
}
diff --git a/src/data/en/api.tsx b/src/data/en/api.tsx
index af20a32f7..c254d1d6d 100644
--- a/src/data/en/api.tsx
+++ b/src/data/en/api.tsx
@@ -1,11 +1,11 @@
import * as React from "react"
import colors from "../../styles/colors"
-import Popup from "../../components/Popup"
-import CodeArea from "../../components/CodeArea"
+import CodeArea, { CodeSandBoxLink } from "../../components/CodeArea"
import useFieldArrayArgument from "../../components/codeExamples/useFieldArrayArgument"
+import generic from "../generic"
import typographyStyles from "../../styles/typography.module.css"
import buttonStyles from "../../styles/button.module.css"
-import code from "../../components/codeExamples/defaultExample"
+import tableStyles from "../../styles/table.module.css"
export default {
title: "API Documentation",
@@ -27,16 +27,20 @@ export default {
),
validateCriteriaMode: (
- <>
-
- When set to firstError (default), only first error from
- each field will be gathered.
-
-
- When set to all, all errors from each field will be
- gathered.
-
- >
+
+
+
+ When set to firstError (default), only first error from
+ each field will be gathered.
+
+
+
+
+ When set to all, all errors from each field will be
+ gathered.
+
- Note: Only registered fields
- with a ref will work. Manually registered inputs won't
- work. eg: {`register({ name: 'test' }) // doesn't work`}{" "}
+ Note: only registered fields
+ with ref will work. Custom register inputs
+ do not apply. eg:{" "}
+ {`register({ name: 'test' }) // doesn't work`}{" "}
+
+
+
+ Note: focus error input order
+ based on register order.
>
),
- nativeValidation: (goToSection) => (
-
- Setting this option to true will enable the browser's
- native validation. You can{" "}
-
- find out more about the built-in browser validation
-
- , and refer to the{" "}
- goToSection("nativeValidation")}
- >
- nativeValidation
- {" "}
- section for more details and examples.
-
+ shouldUnregister: (
+ <>
+
+ By default, when inputs gets removed, React Hook Form use{" "}
+ MutationObserver to detect and unregister{" "}
+ those inputs which gets unmounted. However, you can set{" "}
+ shouldUnregister to false to prevent input
+ state from loss due to unmount.
+
This method will allow you to unregister a single input
- or an array of inputs. This is useful when you used a custom register
- in useEffect and want to unregister it when the component
- unmounts.
+ or an array of inputs.
Note: When you unregister an
@@ -231,7 +237,7 @@ export default {
<>
This method allows you to register input/select Ref and
- validation rules into React Hook Form.
+ apply validation rules into React Hook Form.
Validation rules are all based on HTML standard and also allow custom
@@ -241,7 +247,6 @@ export default {
Important:name{" "}
is required and unique. Input name also supports dot and
bracket syntax, which allows you to easily create nested form fields.
- Example table is below:
>
),
@@ -252,7 +257,7 @@ export default {
borderLeft: `4px solid ${colors.lightPink}`,
}}
>
- If you working on arrays/array fields, you can assign an
+ If you working on simple Array Fields, you can assign an
input name as name[index].{" "}
Check out the Field Array example
- .
+ . For more advance usage, make sure to checkout{" "}
+ useFieldArray.
),
example: "Submit Result",
@@ -287,19 +293,26 @@ export default {
>
react-select
- .
+ . We do provide a component{" "}
+ goToSection("Controller")}
+ >
+ Controller
+ {" "}
+ to take care this process for you.
- By using a custom register call, you will need to update the input
- value with{" "}
+ By using custom register, you will need to update the input value
+ with{" "}
goToSection("setValue")}
>
setValue
- , because input is no longer registered with its ref.
+ .
This object contain information about the form state.
+
This object contains information about the form state.
Important:{" "}
@@ -362,15 +375,36 @@ export default {
{" "}
to improve render performance, so make sure you invoke or read it
before render in order to enable the state update. This
- reduces re-render feature only applies to the Web platform due to a
- lack of support on Proxy at React Native.
+ reduced re-render feature only applies to the Web platform due to a
+ lack of support for Proxy in React Native.
+
+ >
+ ),
+ isDirty: (
+ <>
+ Set to true after the user modified any of the inputs.
+
+ Note: File typed input will
+ need to manage at app level due to the ability to cancel file
+ selection and{" "}
+
+ FileList
+ {" "}
+ object.
>
),
- dirty: "Set to true after a user interacted with any of the inputs.",
- isSubmitted:
- "Set true after a user submitted the form. After a form's submission, its' state will remain submitted until invoked with reset method.",
- dirtyFields: "A unique set of user modified fields.",
+ isSubmitted: (
+ <>
+ Set to true after the user submitted the form. Iits state
+ will remain submitted until the reset method is invoked.
+ >
+ ),
+ dirtyFields: "An object with the user-modified fields.",
touched:
"An object containing all the inputs the user has interacted with.",
isSubmitting: (
@@ -380,7 +414,11 @@ export default {
>
),
submitCount: "Number of times the form was submitted.",
- isValid: "Set to true if the form doesn't have any error.",
+ isValid: (
+ <>
+ Set to true if the form doesn't have any errors.
+ >
+ ),
},
errors: {
title: "errors",
@@ -390,46 +428,36 @@ export default {
Object containing form errors and error messages corresponding to each
input.
-
-
- Note: Difference between V3
- and V4:
-
-
-
-
-
V4: Nested objects
-
- Reason: optional chaining is getting widely
- adopted and allows better support for types..
-
-
- {`errors?.yourDetail?.firstName;`}
-
-
-
-
V3: Flatten object
-
- Reason: simple and easy to access error.
-
-
- {`errors['yourDetail.firstName'];`}
-
-
-
>
),
types: (
<>
- This is useful when you want to return all validation errors for a
- single input. For instance, a password field that is required to have a
- minimum length AND contain a special character. Note that you need to
- set validateCriteriaMode to
- 'all' for this option to work properly.
+
+ This is useful when you want to return all validation errors for a
+ single input. For instance, a password field that is required to have
+ a minimum length and contain a special character.
+
+
+ Note: that you need to set{" "}
+ validateCriteriaMode to all for this option
+ to work.
+
>
),
- message: `If you registered your input with an error message, then it will be put in this field. Otherwise it's an empty string by default.`,
+ message: `If you registered your input with an error message, then it will be put in this field, otherwise it's an empty string by default.`,
ref: `Reference for your input element.`,
+ note: (goToSection) => (
+
+ Note: You can use{" "}
+ goToSection("ErrorMessage")}
+ >
+ ErrorMessage
+ {" "}
+ to help handle your error states
+
+ ),
},
watch: {
title: "watch",
@@ -446,7 +474,7 @@ export default {
When defaultValue is not defined, the first render of{" "}
watch will return undefined because it
is called before register, but you can set the{" "}
- defaultValue as the second argument to return value.
+ defaultValue as the second argument.
The function allows you to manually set one or multiple errors.
-
- Note: This method will not
- persist the error and block the submit action. It's more useful during{" "}
- handleSubmit function when you want to give error
- feedback to the users after async validation.
-
+
The function allows you to manually set one or more errors.
+
+
+
+ This method will not persist the associated input error if the
+ input passes validation.
+
+
+
+
+ Set an error which doesn't associated with an input field and will
+ be persisted. This error must be removed manually with{" "}
+ clearError.
+
+
+
+
+ It's useful during handleSubmit function when you
+ want to give error feedback to the users after async validation.
+
- Note: By invoking this
- method, formState will set the input to{" "}
- touched.
+ You can also set the shouldValidate parameter to{" "}
+ true in order to trigger a field validation.
+
+
+
- You can also set the shouldValidate parameter to{" "}
- true in order to trigger a field validation. eg:{" "}
- setValue('name', 'value', true)
+ You can also set the shouldDirty parameter to{" "}
+ true in order to set field to dirty.
- This function will return the entire form data, and it's useful when
- you want to retrieve form values.
+ This function will help you to read form values. The difference
+ between watch is getValues will not trigger
+ re-render or subscribed to input changes. The functions covers:
- By default getValues() will return form data in a
- flat structure. eg:{" "}
- {`{ test: 'data', test1: 'data1'}`}
+ getValues(): Read entire form values.
- Working on the defined form fields,{" "}
- getValues({`{ nest: true }`}) will return data in a
- nested structure according to input name. eg:{" "}
- {`{ test: [1, 2], test1: { data: '23' } }`}
+ getValues('test'): Read individual input value by
+ name.
+
+
+
+
+ getValues(['test', 'test1']): Read multiple inputs by
+ names.
- If you would like to centralize your validation rules as an external
- validation schema, you can use the validationSchema{" "}
- parameter. React Hook Form currently supports{" "}
-
- Yup
- {" "}
- for object schema validation.
-
- ),
- },
useFieldArray: {
title: "useFieldArray",
description: (
@@ -696,7 +727,57 @@ export default {
to compare controlled vs uncontrolled Field Array.
-
This hook provides the following object and functions.
+
+
+
+
+
{generic.name.en}
+
{generic.type.en}
+
{generic.required.en}
+
{generic.description.en}
+
+
+
+
+
+ name
+
+
+ string
+
+
+
+ <>associated field name.>
+
+
+
+
+ control
+
+
+ Object
+
+
+
{generic.control.en}
+
+
+
+ keyName
+
+
+
+ string = 'id'
+
+
+
+
+ field array key value, default to "id", you can
+ change the key name.
+
+
+
+
+
@@ -710,26 +791,25 @@ export default {
- you can populate the fields by supply{" "}
+ You can populate the fields by supply{" "}
defaultValues at useForm hook.
- make sure you assign id from fields{" "}
+ Make sure you assign id from fields{" "}
object as your component key.
- make sure to set defaultValue to{" "}
- fields[index] when you want to set default value,
- remove or reset with inputs.
+ Make sure to set defaultValue to{" "}
+ fields[index].
- you can not call actions one after another. Actions need to be
+ You can not call actions one after another. Actions need to be
triggered per render.
{
- It doesn't work with custom register at useEffect.
+ It doesn't work with custom register at useEffect or
+ conditional render. For conditional render consider using style to
+ toggle the viability and `validate` function for conditional
+ validation.
Insert input/inputs at particular position and focus.
@@ -842,7 +926,7 @@ React.useEffect(() => {
- (from: number, to: number) => void
+ (from: number, to: number) => void
@@ -855,19 +939,11 @@ React.useEffect(() => {
- (from: number, to: number) => void
+ (from: number, to: number) => void
-
- Move input/inputs to another position.
-
- Note: difference between{" "}
- move and swap, keep calling{" "}
- move will push input/inputs in a circle, while{" "}
- swap only change two input/inputs' position.
-
-
+
Move input/inputs to another position.
@@ -876,13 +952,13 @@ React.useEffect(() => {
- (index?: number | number[]) => void
+ (index?: number | number[]) => void
Remove input/inputs at particular position, or remove all when no
- index is provided.
+ index provided.
>
@@ -902,33 +978,90 @@ React.useEffect(() => {
✓
Unique name of your input.
+
+
+ control
+
+
+ Object
+
+
+
+ control object is from invoking useForm.
+ it's optional if you are using FormContext.
+
+ Controller will inject onChange, onBlur{" "}
+ and value props into the component.
+
+
+
+ Every prop you pass to the Controller component will be forwarded
+ to the component instance you provided with the as{" "}
+ prop. For instance, if you have a custom Switch{" "}
+ component that requires a label prop, you can pass it
+ to the Controller component directly and it will take care of
+ forwarding the prop for you.
+
+ }
+ control={control}
+ name="test"
+/>`}
+ />
- control
+ render
- Object
+ Function
- control object is from invoking useForm.
- it's optional if you are using FormContext.
+ This is a{" "}
+
+ render prop
+
+ . A function that returns a React element and provide the ability to
+ attach events and value into the component. This make it easy to
+ integrate with external controlled component with non-standard props
+ name: onChange, onBlur and{" "}
+ value.
+ (
+
+ ))
+/>
+ } />`}
+ />
@@ -965,107 +1098,38 @@ React.useEffect(() => {
- Validation rules in the same format as for{" "}
- goToSection("register")}
- >
- register
-
- . This object will be cached inside{" "}
- Controller.
-
-
-
-
- onChange
-
-
-
- (args: any | EventTarget) => any
-
-
-
-
- This prop allows you to customize the return value, make sure you
- aware the shape of the external component value props.{" "}
- value or checked attribute will be read
- when payload's shape is an object which contains{" "}
- type attribute.
+ Validation rules in the same format as for register.
event.target.value}}
-onChange={{([ { checked } ]) => ({ checked })}}`}
+ rawData="rules={{ required: true }}"
/>
-
-
- onChangeName
-
-
- string
-
-
-
- This prop allows you to target a specific event name for{" "}
- onChange, eg: when onChange event is named{" "}
- onTextChange
-
-
onFocus
- () => void
+ () => void
-
+
This callback allows the custom hook to focus on the input when
there is an error. This function is applicable for both React and
React-Native components as long as they can be focused.
- This prop allows you to target a specific event name for{" "}
- onBlur, eg: when onBlur event is named{" "}
- onTextBlur
-
-
-
-
- valueName
-
-
- string
-
-
-
- This prop allows you to support inputs that doesn't use a prop
- called value. eg: checked,{" "}
- selected and etc.
+
+
@@ -1102,15 +1166,6 @@ onChange={{([ { checked } ]) => ({ checked })}}`}
. This wrapper component will make it easier for you to work with
them.
-
- Every prop you pass to the Controller component will be forwarded to
- the component instance you provided with the as prop. For
- instance, if you have a custom Switch component that
- requires a label prop, you can pass it to the Controller
- component directly and it will take care of forwarding the prop for
- you. The name prop will be used mainly to access the
- value through the form later.
-
- The following example demonstrates how you can leverage the browser's
- validation. You only need to set nativeValidation to{" "}
- true and the rest of the syntax is the same as standard
- validation.
-
-
- Note: This feature has been
- removed in V4 due to low usage, but you can still use it in V3
-
- >
- ),
+ table: {
+ name: <>associated field name.>,
+ errors: (
+ <>
+ errors object from React Hook Form. It's optional if you
+ are using FormContext.
+ >
+ ),
+ message: <>inline error message.>,
+ as: (
+ <>
+ Wrapper component or HTML tag. eg: as="span" or{" "}
+ {`as={}`}
+ >
+ ),
+ render: (
+ <>
+ This is a{" "}
+
+ render prop
+ {" "}
+ for rendering error message or messages.
+
+ Note: you need to set{" "}
+ validateCriteriaMode to 'all' for using messages.
+
This function allow you to run any external validation methods, such
as{" "}
+
+ Yup
+
+ ,{" "}
({ checked })}}`}
- Note: make sure you are
- returning object which contains values and{" "}
- errors, and their default value should be{" "}
- {`{}`}.
+ We support Yup, Joi and Superstruct officially as{" "}
+
+ standard resolvers
+
+ .
-
- Note: returning errors
- object's key should be relevant to your inputs.
-
+
+ npm install @hookform/resolvers
+
- Note: this function will be
- cached inside the custom hook similar as validationSchema
- , while validationContext is a mutable object which can
- be changed on each re-render.
+ Notes on building custom
+ resolver:
-
- Note: re-validate input will
- only occur one field at time during user’s interaction, because the
- lib itself will evaluate the error object to the specific field and
- trigger re-render accordingly.
-
+
+
+
+ Make sure you are returning object which contains{" "}
+ values and errors, and their default
+ value should be {`{}`}.
+
+
+
+
+
+ Returning errors object's key should be relevant to your inputs.
+
+
+
+
+
+ This function will be cached inside the custom hook, while{" "}
+ context is a mutable object which can be
+ changed on each re-render.
+
+
+
+
+
+ Re-validate input will only occur one field at time during user’s
+ interaction, the lib itself will evaluate the error object to
+ trigger re-render accordingly.
+
+ Share the same functionality as watch API, however, this
+ will isolate re-render at your component level and potentially result in
+ better performance for your application.
+
+ ),
+ },
}
diff --git a/src/data/en/devtools.tsx b/src/data/en/devtools.tsx
index dc435f937..3bc08b17f 100644
--- a/src/data/en/devtools.tsx
+++ b/src/data/en/devtools.tsx
@@ -8,7 +8,7 @@ export default {
step1: (
<>
Step 1: install{" "}
- react-hook-form-devtools as a dev dependency package.
+ @hookform/devtools as a dev dependency package.
>
),
step2: (
diff --git a/src/data/en/faq.tsx b/src/data/en/faq.tsx
index 57aef3036..9f052ca09 100644
--- a/src/data/en/faq.tsx
+++ b/src/data/en/faq.tsx
@@ -3,7 +3,6 @@ import colors from "../../styles/colors"
import enzymeInput from "../../components/codeExamples/enzymeInput"
import focusController from "../../components/codeExamples/focusController"
import toggleFields from "../../components/codeExamples/toggleFields"
-import virtualizedList from "../../components/codeExamples/virtualizedList"
import CodeArea from "../../components/CodeArea"
import typographyStyles from "../../styles/typography.module.css"
import tableStyles from "../../styles/table.module.css"
@@ -22,11 +21,11 @@ export default {
Performance is one of the primary goals for building this custom hook.
React Hook Form relies on uncontrolled component, hence the reason why
- the register function occurs at the ref. This approach will reduce the
- amount of re-rendering occurring due to user typing or value changing.
- Components mount to the page is much quicker as well because they are
- not controlled. For mounting speed, I have completed a quick
- comparison test which you can refer to by{" "}
+ the register function occurs at the ref.
+ This approach will reduce the amount of re-rendering occurring due to
+ user typing or value changing. Components mount to the page is much
+ quicker as well because they are not controlled. For mounting speed, I
+ have completed a quick comparison test which you can refer to by{" "}
defaultValue or{" "}
defaultChecked to an individual field. However, the hook
itself does provide an easier way to initialise all input values too.
- Example below:
),
},
@@ -121,8 +119,7 @@ export default {
React Hook Form needs ref to collect the input value,
however, you may want to use ref for other purposes (e.g.
- scroll into the view, or focus). The following example will show you
- how.
+ scroll into the view, or focus).
),
},
@@ -133,7 +130,7 @@ export default {
You can actually register an input without a{" "}
ref. In fact, you can manually setValue,{" "}
- setError and triggerValidation.
+ setError and trigger.
+ Why is testing not working with React Native (
+ react-native-testing-library)?
+
+
+
+ React Hook Form doesn't register input during server side
+ render, which means testing in react native could result{" "}
+ window object been undefined, quick
+ fix would be just stub window object to enable the
+ registration progress.
+
+
Why am I getting act warning?
@@ -509,7 +537,7 @@ export default {
),
},
{
- title: "Controller not working with submitFocusError?",
+ title: "Controller not working with shouldFocusError?",
description: (
<>
@@ -522,7 +550,7 @@ export default {
- However, for some 3rd party controlled Components like{" "}
+ However, for some 3rd party controlled Components (like{" "}
{``} from MUI or {``}{" "}
from AntD) it's very difficult to predict his ref because the
formats changes, so React Hook Form will properly detect the
@@ -541,10 +569,48 @@ export default {
If you find difficult to make the autofocus with external controlled
component. It is possible to disable the "autofocus on error"
feature. Maybe this behavior will bring a better user experience in
- some cases. {`useForm({submitFocusError: false});`}
+ some cases. {`useForm({shouldFocusError: false});`}
>
),
},
+ {
+ title: "How to work with modal or tab forms?",
+ description: (
+ <>
+
+ It's important to understand React Hook Form embrace native form
+ behavior by store input state inside each input (except custom
+ register at useEffect). One of the common
+ misconceptions is when working with modal or tab forms, by mounting
+ and unmounting form/inputs that inputs state will remain. That's
+ incorrect implementation instead the correct solution should always
+ building a new form for your form inside modal or each tab and
+ capture your submission data in local or global state.
+
+ >
+ ),
+ },
],
}
diff --git a/src/data/en/getStarted.tsx b/src/data/en/getStarted.tsx
index c7250f517..04c50e720 100644
--- a/src/data/en/getStarted.tsx
+++ b/src/data/en/getStarted.tsx
@@ -3,8 +3,12 @@ import code from "../../components/codeExamples/defaultExample"
import { Link } from "@reach/router"
import translateLink from "../../components/logic/translateLink"
import CodeArea from "../../components/CodeArea"
-import { uiLibraryHookInput } from "../../components/codeExamples/getStarted"
+import {
+ uiLibraryHookInput,
+ uiLibraryHookInputTs,
+} from "../../components/codeExamples/getStarted"
import typographyStyles from "../../styles/typography.module.css"
+import VideoList from "../../components/VideoList"
export default {
title: "Get Started",
@@ -34,7 +38,7 @@ export default {
register{" "}
- your uncontrolled component into the Hook. This will make its value
+ your uncontrolled component into the hook. This will make its value
available for both the form validation and submission.
@@ -49,8 +53,7 @@ export default {
require you to either use a manual register command:{" "}
{`register({ name: 'test' }, { required: true })`} or a{" "}
Controller to wrap and register your
- component automatically. Learn more in the dedicated section for{" "}
- React Native.
+ component.
>
),
@@ -150,20 +153,27 @@ export default {
<>
React Hook Form has made it easy to integrate with external UI
- component libraries. You can check out{" "}
-
- this video tutorial
- {" "}
- on how to work with MUI.
+ component libraries. You can check out the follow videos.
+
+
+
Option 1: The best way is to
- check if the component you wish to use exposes an{" "}
- innerRef or ref that can be used to{" "}
+ check if the component you wish to use exposes an ref{" "}
+ that can be used to{" "}
register
@@ -174,11 +184,7 @@ export default {
register to it.
-
- {
- ''
- }
-
+ {''}
Option 2: Sometimes
@@ -190,7 +196,12 @@ export default {
Controller wrapper component, which
will take care of the registration process for you.
-
+
Option 3: Lastly we can set
up a custom register using the{" "}
@@ -214,7 +225,13 @@ export default {
},
globalState: {
title: "Integrate global state",
- description: `React Hook Form doesn't require you to rely on a state management library such as Redux to store your data, but you can easily integrate with it:`,
+ description: (
+
+ React Hook Form doesn't require you to rely on a state management
+ library such as Redux to store your data, but you can easily integrate
+ with it:
+
+ ),
},
reactNative: {
title: "React Native",
@@ -223,8 +240,8 @@ export default {
You will get the same performance enhancement from an Uncontrolled
Component. However, there are certain APIs which are not compatible with
React Native (due to the API differences between web and native). You
- will have to use a manual register as shown in the following
- example.
+ will have to use Controller or custom register as
+ shown in the following example.
),
},
@@ -237,13 +254,64 @@ export default {
),
},
+ schema: {
+ title: "Schema Validation",
+ description: (
+ <>
+
+ React Hook Form supports schema-based form validation with{" "}
+
+ Yup
+
+ ,{" "}
+
+ Superstruct
+ {" "}
+ &{" "}
+
+ Joi
+
+ , where you can pass your schema to{" "}
+ useForm as an optional config. React Hook
+ Form will validate your input data against the schema and return with
+ either errors or a valid result.
+
+ >
+ ),
+ step1: (
+ <>
+
+ Step 1: Install{" "}
+ Yup into your project.
+
+ >
+ ),
+ step2: (
+
+ Step 2: Prepare your schema for
+ validation and register inputs with React Hook Form.
+
React Hook Form provides an errors object to show you the
errors in the form.
- >
+
),
},
}
diff --git a/src/data/en/migrateV5ToV6.tsx b/src/data/en/migrateV5ToV6.tsx
new file mode 100644
index 000000000..1f7b9d9f3
--- /dev/null
+++ b/src/data/en/migrateV5ToV6.tsx
@@ -0,0 +1,288 @@
+import CodeArea from "../../components/CodeArea"
+import validationSchema from "../../components/codeExamples/validationSchema"
+import * as React from "react"
+import typographyStyles from "../../styles/typography.module.css"
+
+export default (
+ <>
+
Hi there,
+
+ Here are the breaking changes you would need to adjust. We sincerely hope
+ those changes aren't creating too much trouble for your codebase. If you
+ are wondering some of the rationals behind, you can take a look at this{" "}
+
+ pull request
+ {" "}
+ for more details.
+
+
+
+ ❤️ React hook Form Team
+
+
+
+
+
+
+
+
useForm:
+
+
+
+ We are removing validation prefix for all the config.
+
+
+
+
+
+
+
validationSchema:
+
+
+ validationSchema has been replace with standard{" "}
+ resolver, and you can use Yup, Joi and Superstruct at the
+ moment. We have an official resolver library to support more schema
+ validation in the future.
+
+
+
+ npm install @hookform/resolvers
+
+
+
+
+
+
Controller:
+
+
+ We made Controller's API much simpler, and the following
+ props have been removed and replaced with render props.
+
+ This type is useful when you are using Context's{" "}
+ Consumer instead of
+ useFormContext hook.
+
+ ),
+ },
+}
diff --git a/src/data/es/advanced.tsx b/src/data/es/advanced.tsx
index 2ca75884f..e287edec4 100644
--- a/src/data/es/advanced.tsx
+++ b/src/data/es/advanced.tsx
@@ -3,6 +3,7 @@ import CodeArea from "../../components/CodeArea"
import accessibleCodeBase from "../../components/codeExamples/accessibleCodeBase"
import accessibleCodeFinal from "../../components/codeExamples/accessibleCodeFinal"
import { step1, step2, step3 } from "../../components/codeExamples/formWizard"
+import * as CodeExampleTestingForm from "../../components/codeExamples/testingForm"
import smartForm from "../../components/codeExamples/smartForm"
import form from "../../components/codeExamples/form"
import input from "../../components/codeExamples/input"
@@ -219,8 +220,8 @@ export default {
<>
La idea aquí es que puedas componer fácilmente tu formulario con
- entradas. Vamos a crear un componente de Formulario {" "}
- para recopilar automáticamente los datos del formulario.
+ entradas. Vamos a crear un componente de Formulario para
+ recopilar automáticamente los datos del formulario.
La responsabilidad de los componentes Input es registrarse en {""}
- react-hook-form .
+ react-hook-form.
- Note: we have also build a
- custom hook for complex scenario:{" "}
+ Nota: tambien hemos
+ construido a custom hook for complex scenario:{" "}
useFieldArray.
@@ -302,44 +303,11 @@ export default {
>
link para esa implementación.
{" "}
- con Controller.
+ con Controller.
>
),
},
- schema: {
- title: "Validación del Schema",
- description: (
- <>
-
- React Hook Form soporta validación de formularios basada en esquemas
- con{" "}
-
- Yup
-
- , donde puedes pasar tu validationSchema a{" "}
- useForm como configuración opcional. React
- Hook Form validará los datos de tus inputs contra el esquema y
- retornará los errores o el resultado válido
- según corresponda.
-
- >
- ),
- step1: (
- <>
-
- Paso 1: Agregá{" "}
- Yup en tu proyecto.
-
- >
- ),
- step2: (
-
- Paso 2:Crea tu esquema de
- validación y registra los inputs en React Hook Form.
-
- ),
- },
connectForm: {
title: "Connect Form",
description: (
@@ -419,7 +387,7 @@ export default {
. Resuelve el problema donde los datos pasan a través de un árbol de
componentes sin tener que pasar propiedades manualmente en todos los
niveles. Esto hace que el árbol de componentes active una nueva
- renderización cuando React Hookv Form dispara una actualización de
+ renderización cuando React Hook Form dispara una actualización de
estado, pero aún podemos optimizar nuestra aplicación si es necesario
como en el ejemplo a continuación.
@@ -449,7 +417,7 @@ export default {
),
},
workingWithVirtualizedList: {
- title: "Working with virtualized list",
+ title: "Trabajando con listas vitualizadas",
description: (
<>
+ Las pruebas son muy importantes porque preservan el código de los
+ bichos o y garantizar la seguridad del código cuando se refactoriza la
+ base del código.
+
+
+
+ Recomendamos el uso de la{" "}
+
+ testing-library
+
+ , porque es simple y las pruebas se centran más en el comportamiento
+ del usuario.
+
+
+
♦
+
+
+ Step 1: Prepare su entorno de
+ pruebas.
+
+
+
+ Por favor instale mutationobserver-shim porque
+ react-hook-form use MutationObserver para detectar las
+ entradas obtenidas desmontado del DOM.
+
+
+
+
+
+ Crear setup.js para importar{" "}
+ mutaciónobservador-shim.
+
+
+
+
+ Finalmente, tienes que actualizar setup.js en{" "}
+ jest.config.js para incluir el archivo.
+
+
+
+
+
+ Step 2: Crear un formulario
+ de acceso.
+
+
+
+ Hemos establecido el atributo del papel en consecuencia. Estos
+ atributos son útiles cuando se escriben pruebas y se mejora la
+ accesibilidad. Para más información, puedes consultar la documentación
+ de la{" "}
+
+ testing-library
+
+ .
+
+
+
+
+
+ Step 3: Write tests.
+
+
+
+ Los siguientes criterios son los que intentamos cubrir con las
+ pruebas:
+
+
+
+
+
Fallo en la presentación de la prueba.
+
+
+ Estamos usando el método esperaPor y{" "}
+ encuentra* para detectar la retroalimentación de la
+ presentación porque manejarSometer se ejecuta
+ asincrónicamente.
+
+
+
+
Validación de la prueba asociada a cada entrada.
+
+
+ Estamos usando el método *ByRole cuando buscamos
+ diferentes elementos porque así es como los usuarios reconocen su
+ componente de UI.
+
+
+
+
Prueba de presentación exitosa.
+
+
+
+
+ >
+ ),
+ },
}
diff --git a/src/data/es/api.tsx b/src/data/es/api.tsx
index 04bd8cec6..a86932f86 100644
--- a/src/data/es/api.tsx
+++ b/src/data/es/api.tsx
@@ -1,26 +1,19 @@
import * as React from "react"
-import { Link as NavLink } from "gatsby"
import colors from "../../styles/colors"
-import translateLink from "../../components/logic/translateLink"
-import Popup from "../../components/Popup"
import CodeArea from "../../components/CodeArea"
import useFieldArrayArgument from "../../components/codeExamples/useFieldArrayArgument"
import typographyStyles from "../../styles/typography.module.css"
import buttonStyles from "../../styles/button.module.css"
-import code from "../../components/codeExamples/defaultExample"
+import tableStyles from "../../styles/table.module.css"
+import generic from "../generic"
export default {
title: "Documentación de la API",
header: {
- description: "se enfoca en proveer la mejor DX simplificando la API.",
+ description: "Se enfoca en proveer la mejor DX simplificando la API.",
},
useForm: {
title: "useForm",
- intro: (
- <>
- Invocando useForm, recibirás los siguientes métodos{" "}
- >
- ),
description: (
useForm también tiene argumentos opcionales. El
@@ -47,10 +40,8 @@ export default {
validateContext: (
<>
- This context object will be injected into{" "}
- validationResolver's second argument or Este objeto de
- contexto se inyectará en El segundo argumento de{" "}
- validationResolver o
+ Este objeto de contexto se inyectará en el segundo argumento del
+ resolutor o en el objeto de contexto de validación{" "}
Yup
- objeto de contexto de validación.
+ .
- Con la configuración seteada en all, se correran todas
- las validaciones de los campos y reunirá todos los errores
+ Con la configuración configurada en all, se correran
+ todas las validaciones de los campos y reunirá todos los errores
encontrados.
>
@@ -95,10 +86,17 @@ export default {
Considera que es una mala práctica de performance.
>
),
+ validationOnAll: (
+ <>
+ La validación se activará en blur y change{" "}
+ eventos. Advertencia: como con el onChange modo,{" "}
+ all puede tener un impacto significativo en el rendimiento.
+ >
+ ),
defaultValues: (goToSection) => (
<>
- Puedes setear el valor por defecto del input con{" "}
+ Puedes configurar el valor por defecto del input con{" "}
defaultValue/defaultChecked{" "}
- Nota:múltiples radio input
- con el mismo nombre, desea registrar la validación hasta el último
- input para que el hook entienda validarlos como un grupo al final.
+ También puede establecer el parámetro shouldDirty en
+ true para configurar el campo como sucio.
+
+
>
),
},
@@ -349,18 +338,18 @@ export default {
max: "El valor máximo a aceptar para este input.",
min: "El valor mínimo a aceptar para este input.",
pattern: "El patrón regex para este input.",
- validate: `Puedes pasar una función callback commo argumento para validar, o puedes pasar un objeto de funciones callback para validar todas ellas. (consulta los ejemplos)`,
+ validate: `Puedes pasar una función callback como argumento para validar, o puedes pasar un objeto de funciones callback para validar todas ellas. (consulta los ejemplos)`,
},
},
formState: {
title: "formState",
description: (
<>
-
Este objeto contiene informacioón sobre el estado del formulario.
+
Este objeto contiene información sobre el estado del formulario.
- Important:{" "}
- formState is wrapped with{" "}
+ Importante:{" "}
+ formState es envuelto con{" "}
Proxy
{" "}
- to improve render performance, so make you have invoke/read it before
- render in order to enable the state update. Esta La
- función de reducción de la función de renderizado solo se aplica a la
- plataforma web debido a una falta de soporte en Proxy en
- React Native.
+ para mejorar el rendimiento, tambien se puede hacer invocando antes un
+ render con este orden es capaz de actualizar el estado.
+ Esta es una función de la reducción del renderizado solo se aplica a
+ la plataforma web debido a una falta de soporte en Proxy{" "}
+ en React Native.
>
),
dirty:
- "Se setea en verdader luego que el usuario haya interactuado con algún input.",
+ "Se configura un verdader luego que el usuario haya interactuado con algún input.",
dirtyFields: "Un conjunto único de campos modificados por el usuario.",
isSubmitted:
- "Se setea a verdadero luego que el usuario envia el formulario. Después del envío de un formulario, su estado permanecerá enviado hasta que se invoque con el método de reinicio.",
+ "Se configura a verdadero luego que el usuario envia el formulario. Después del envío de un formulario, su estado permanecerá enviado hasta que se invoque con el método de reinicio.",
touched: "Un objeto con todos los inputs con los que se interactuó.",
isSubmitting: (
<>
- Durante el envio del formulario se setea en verdadero y
- luego del envio se setea en falso
+ Durante el envio del formulario se configura en verdadero y
+ luego del envio se configura en falso
>
),
submitCount: "Número de envios de formulario.",
- isValid: "Se setea en verdadero si no tiene ningún error.",
+ isValid: "Se configura un verdadero si no tiene ningún error.",
},
errors: {
title: "errors",
@@ -399,16 +388,6 @@ export default {
Objeto que contiene los errores de formulario o los mensajes de error
que pertenecen a cada input.
-
-
- Nota: Puedes aprender más en{" "}
-
- Mensaje de error
- {" "}
- de la página de uso avanzado.
-
>
),
types: (
@@ -416,11 +395,23 @@ export default {
Esto es útil para validaciones de inputs como reglas de contraseña,
cuando múltiples errores deben retornarse para un solo campo. Para
habilitar esta función, asegúrese de haber configurado{" "}
- validateCriteriaMode: 'all'.
+ criteriaMode 'all'.
>
),
message: `Message es un string vacio por defecto. Sin embargo, si registra la validación con un mensaje de error, se devolverá.`,
ref: `Referencia del input.`,
+ note: (goToSection) => (
+
+ Nota: puede usar{" "}
+ goToSection("ErrorMessage")}
+ >
+ ErrorMessage
+ {" "}
+ para ayudar a manejar sus estados de erro
+
+ ),
},
watch: {
title: "watch",
@@ -437,8 +428,8 @@ export default {
Cuando defaultValue no es definido, el primer
renderizado de watch retornará undefined{" "}
porque es llamado antes de register, pero puedes
- setear el defaultValue como segundo argumento para
- retornar el valor.
+ configurar el defaultValue como segundo argumento
+ para retornar el valor.
@@ -468,7 +459,6 @@ export default {
),
multiple: "Observa multiples inputs",
all: "Observa todos los inputs",
- nest: "Observa todos los inputs y retorna objetos anidados",
},
},
handleSubmit: {
@@ -477,7 +467,7 @@ export default {
<>
Esta función pasará los datos del formulario cuando la validación haya
- sido exitosa Y puede ser invocada remotamente también.
+ sido exitosa y puede ser invocada remotamente también.
La función te permite setear manualmente uno o varios errores.
-
- Nota:: Este método no
- persistirá el error y bloqueará La acción de envío. Es más útil
- durante la función handleSubmit cuando desea dar
- comentarios de error a los usuarios después de la validación
- asíncrona.
-
+
+
+
+ Este método no persistirá el error de entrada asociado si la
+ entrada pasar validación.
+
+
+
+
+ Establecer un error que no esté asociado con un campo de entrada
+ será persiste y es necesario eliminarlo manualmente con{" "}
+ clearError.
+
+
+
+
+ Es útil durante la función handleSubmit cuando desea
+ dar comentarios de error a los usuarios después de la validación
+ asíncrona.
+
- Esta función te permite setear dinámicamente los valores de
+ Esta función te permite configurar dinámicamente los valores de
input/select. Al mismo tiempo, trata de evitar renderizaciones cuando
no son necesarias y solo bajo las siguientes condiciones:
@@ -592,13 +597,7 @@ export default {
Cuando setValue es invocado por primera vez y formState{" "}
- dirty está seteado en verdadero
-
-
-
-
- Cuando setValue is invocado y formState touched es
- actualizado.
+ dirty está configurado en verdadero
- Esta función retornará todos los datos del formulario, y es útil en
- funciones en los que quieras retornar todo los valores del formulario.
+ Esta función lo ayudará a leer los valores de los formularios. La
+ diferencia entre watch es getValues no se
+ activará volver a procesar o suscribirse a los cambios de entrada. Las
+ funciones cubren:
- Por defecto getValues() retornará los datos del
- formulario en una estructura plana. ej:{" "}
- {`{ test: 'data', test1: 'data1'}`}
+ getValues (): lea valores de formulario completos.
+
+
+
+
+ getValues('test'): lea el valor de entrada
+ individual por name.
- Trabajando en los campos de formulario definidos,{" "}
- getValues({`{ nest: true }`}) retornará los datos en
- una estructura anidada de acuerdo al name del input.
- ej: {`{ test: [1, 2], test1: { data: '23' } }`}
+ getValues(['test', 'test1']): lee múltiples
+ entradas por name.
- Si quieres centralizar tus reglas de validación con una librería de
- validación de esquemas, puedes setear validationSchema en{" "}
- useForm como argumento opcional. React Hook Form
- actualmente soporta{" "}
-
- Yup
- {" "}
- para validación de esquema de objeto.
-
- Componente controlado. ej: as="input" or{" "}
- {`as={}`}
+ El controlador inyectará onChange, onBlur{" "}
+ y value apoyos en el componente.
+ }
+ control={control}
+ name="test"
+ />
+ `}
+ />
- control
+ render
- Object
+ Function
-
✓
+
- El objeto control es obtenido al invocar{" "}
- useForm.
+ Esto es un{" "}
+
+ render prop
+
+ . Una función que devuelve un elemento React y proporciona la
+ capacidad de adjunte eventos y valor al componente. Esto hace que
+ sea fácil integrarse con un componente controlado externo con
+ accesorios no estándar nombre: onChange,{" "}
+ onBlur yvalue.
+ (
+
+ ))
+ />
+ } />`}
+ />
@@ -742,8 +774,7 @@ export default {
Note: si tu formulario lo
hará invoque reset con diferentes valores, deberá
proporcionar defaultValues en el nivel useForm en
- lugar de set
- defaultValue en línea.
+ lugar de set defaultValue en línea.
@@ -757,49 +788,34 @@ export default {
Reglas de validación conforme a register.
-
-
-
-
- onChange
-
-
-
- (args: any | EventTarget) => any
-
-
-
-
- Esta propiedad onChange te permitirá customizar el
- valor de retorno, asegúrese de conocer la forma de los accesorios
- del componente externo value.
+
+
+ Estado local: entrada register con validación
+ actualizada reglas o unregister en{" "}
+ useEffect y dejar que Controller se
+ vuelva a registrar con las rules actualizadas.
+
+
+ Estado de entrada: aproveche la función validate{" "}
+ con getValues para devolver su validación
+ condicionalmente.
+
+
event.target.value}}
-onChange={{([ event, data ]) => ({ checked: data.checked})}}`}
+ rawData="
+ register('name', { required: state })
+ validate: (value) => value === getValues('firstName');"
/>
-
-
- onChangeName
-
-
- string
-
-
-
- Esta propiedad te permite setear el nombre onChange específico del
- objeto wrappeado, por ejemplo, cuando el evento{" "}
- onChange se llama onTextChange
-
- Esta propiedad te permite setear el nombre onBlur específico del
- objeto wrappeado, por ejemplo, cuando el evento onBlur
- se llama onTextBlur
-
-
),
description: (
@@ -879,14 +881,14 @@ onChange={{([ event, data ]) => ({ checked: data.checked})}}`}
Form context está destinado a resolver el problema cuando hay inputs
anidados profundamente en el árbol de componentes y pasar métodos hasta
el fondo como {""}
- propiedades se vuelve tedioso.
+ propiedades se vuelve tedioso.
),
description: (
<>
- Una vez que el formulario es wrappeado con FormContext,
- la function{" "}
+ Una vez que el formulario es envuelto con FormContext, la{" "}
+ function{" "}
useFormContext
puede ser invocada desde sus componentes hijos.
- El siguiente ejemplo muestra cómo puedes aprovechar la validación
- nativa del navegador. Solo necesitas establecer{" "}
- nativeValidation en {""}
- true y el resto de la sintaxis es la misma que la
- validación estándar.
-
-
- Note: This feature has been
- removed in V4 due to low usage, but you can still use it in V3
-
- >
- ),
+ table: {
+ name: <>Nombre de campo asociado.>,
+ errors: (
+ <>
+ Objeto errors de React Hook Form
+ >
+ ),
+ message: <>mensaje de error en línea.>,
+ as: (
+ <>
+ Componente wrappeado o un tag HTML. ej: as="span" o{" "}
+ {`as={}`}
+ >
+ ),
+ render: (
+ <>
+ Esto es un{" "}
+
+ render prop
+ {" "}
+ para rendericación de mensajes o errores.
+
+ Nota: Necesitas usar{" "}
+ validateCriteriaMode para 'all' para usar messages.
+
+ >
+ ),
+ },
},
useFieldArray: {
title: "useFieldArray",
@@ -1029,12 +968,66 @@ onChange={{([ event, data ]) => ({ checked: data.checked})}}`}
para comparar Field Arrays controlados vs. no-controlados.
+
+
+
+
+
{generic.name.en}
+
{generic.type.es}
+
{generic.required.es}
+
{generic.description.es}
+
+
+
+
+
+ name
+
+
+ string
+
+
+
+ <>
+ <>Nombre de campo asociado.>
+ >
+
+
+
+
+ control
+
+
+ Object
+
+
+
{generic.control.es}
+
+
+
+ keyName
+
+
+
+ string = 'id'
+
+
+
+
+ campo matriz key valor, predeterminado en "id",
+ puede cambiar el nombre de la clave
+
+
+
+
+
+
Este hook provee el siguiente objeto y funciones.
- Important:
+ Importante: useFieldArray está construido sobre componentes no
controlados. Las siguientes notas lo ayudarán a conocer y tener en
cuenta su comportamiento durante la implementación.
@@ -1043,7 +1036,7 @@ onChange={{([ event, data ]) => ({ checked: data.checked})}}`}
- puedes inicializar los (campos) fields seteando{" "}
+ puedes inicializar los (campos) fields configurado{" "}
defaultValues en useForm hook.
make sure to set defaultValue to{" "}
- fields[index] when you want to set default value,
- remove or reset with inputs.
+ fields[index] Cuando se quieren configurar los
+ valores por defecto, remover o setear con inputs.
@@ -1068,32 +1061,32 @@ onChange={{([ event, data ]) => ({ checked: data.checked})}}`}
{
- if (fields.length === 2) {
- remove(0);
- }
- append({ test: 'test' });
-}}
+ handleChange={() => {
+ if (fields.length === 2) {
+ remove(0);
+ }
+ append({ test: 'test' });
+ }}
-// ✅ The following is correct and second action is triggered after next render
-handleChange={() => {
- append({ test: 'test' });
-}}
+ // ✅ The following is correct and second action is triggered after next render
+ handleChange={() => {
+ append({ test: 'test' });
+ }}
-React.useEffect(() => {
- if (fields.length === 2) {
- remove(0);
- }
-}, fields)
+ React.useEffect(() => {
+ if (fields.length === 2) {
+ remove(0);
+ }
+ }, fields)
`}
/>
- It's important to apply{" "}
- {`ref={register()}`} instead of{" "}
- {`ref={register}`} when working with{" "}
- useFieldArray so register will get
+ Es importante aplicar{" "}
+ {`ref={register()}`} en lugar de{" "}
+ {`ref={register}`} cuando se trabaja con{" "}
+ useFieldArray entonces register will get
invoked during map.
@@ -1122,7 +1115,7 @@ React.useEffect(() => {
Importante: debido a que
las entradas pueden ser no-controladas, se requiere{" "}
- id con componentes mapeados para ayudar a React a
+ id con componentes mapeados para ayudar a React a
identificar qué elementos se han cambiado, agregado o eliminado.
Inserta input/inputs en una posición en particular.
@@ -1169,7 +1163,7 @@ React.useEffect(() => {
- (from: number, to: number) => void
+ (from: number, to: number) => void
Intercambia las posiciones de los input/inputs.
@@ -1180,7 +1174,7 @@ React.useEffect(() => {
- (from: number, to: number) => void
+ (from: number, to: number) => void
@@ -1200,24 +1194,32 @@ React.useEffect(() => {
- (index?: number | number[]) => void
+ (index?: number | number[]) => void
- Elimina input/inputs en una posición en particular, or elimina todos
+ Elimina input/inputs en una posición en particular, o elimina todos
cuando no se proporciona un index.
Esta función le permite ejecutar cualquier método de validación
externo, tal como{" "}
+
+ Yup
+
+ ,{" "}
{
>
Superstruct
{" "}
- y etc. De hecho, el objetivo no es solo limitado Sí como nuestro
+ y etc. De hecho, el objetivo no es solo limitado sí como nuestro
externo (esquema) biblioteca de validación. Nos gustaría apoyar a
muchos otros bibliotecas de validación para trabajar con React Hook
Form. Incluso puedes escribir su lógica de validación personalizada
@@ -1241,32 +1243,77 @@ React.useEffect(() => {
- Nota: asegúrate de que eres
- devolver objeto que contiene values y errors
- , y su valor predeterminado debe ser un objeto vacío{" "}
- {`{}`} .
+ Apoyamos a Yup, Joi y Superstruct oficialmente como{" "}
+
+ solucionadores estándar
+
+ .
-
- Nota: errores de retorno La
- clave del objeto debe ser relevante para sus entradas.
-
+
+ npm install @hookform/resolvers
+
-
- Nota: esta función se
- almacenará en caché dentro del enlace personalizado, similar a{" "}
- validationSchema, mientras que{" "}
- validationContext es un objeto mutable que se puede
- cambiar en cada representación.
-
+
notas sobre la creación de solucionadores personalizados:
-
- Nota: volver a validar la
- entrada solo ocurre un campo a la vez durante la interacción del
- usuario, porque el lib mismo evaluará el objeto de error en el campo
- específico y desencadenar re-renderizar en consecuencia.
-
+
+
+
+ Nota: asegúrate de que
+ eres devolver objeto que contiene values y{" "}
+ errors, y su valor predeterminado debe ser un objeto
+ vacío {`{}`}.
+
+
+
+
+
+ Nota: errores de retorno
+ La clave del objeto debe ser relevante para sus entradas.
+
+
+
+
+
+ Nota: esta función se
+ almacenará en caché dentro del enlace personalizado, mientras que{" "}
+ context es un objeto mutable que se puede cambiar en
+ cada representación.
+
+
+
+
+
+ Nota: volver a validar la
+ entrada solo ocurre un campo a la vez durante la interacción del
+ usuario, porque el lib mismo evaluará el objeto de error en el
+ campo específico y desencadenar re-renderizar en consecuencia.
+
+ Comparta la misma funcionalidad que la API watch, sin
+ embargo, esto aislará el renderizado en el nivel de su componente y
+ potencialmente resultará en Mejor rendimiento para su aplicación.
+
+ ),
+ },
}
diff --git a/src/data/es/devtools.tsx b/src/data/es/devtools.tsx
index 87f153a52..ab05ce0a6 100644
--- a/src/data/es/devtools.tsx
+++ b/src/data/es/devtools.tsx
@@ -9,7 +9,7 @@ export default {
step1: (
<>
Paso 1: Instalar en pc{" "}
- react-hook-form-devtoolscomo un paquete de dependencia de
+ @hookform/devtoolscomo un paquete de dependencia de
desarrollo.
>
),
@@ -17,7 +17,7 @@ export default {
<>
Paso 2:
Integrate con tu React La aplicación es tan simple como importar un
- Componente a su aplicación / Formulario y pasar control {" "}
+ Componente a su aplicación / Formulario y pasarcontrol{" "}
apuntalarlo.
>
),
diff --git a/src/data/es/faq.tsx b/src/data/es/faq.tsx
index 56acfbf4d..664be68c6 100644
--- a/src/data/es/faq.tsx
+++ b/src/data/es/faq.tsx
@@ -107,8 +107,8 @@ export default {
React Hook Form se basa en componentes no controlados. En un
componente no controlado, puedes especificar el valor por defecto de
- un campo individual mediante defaultValue o{" "}
- defaultChecked . Sin embargo, el Hook proporciona una
+ un campo individual mediante defaultValue o{" "}
+ defaultChecked. Sin embargo, el Hook proporciona una
manera más fácil de inicializar todos los valores de entrada. Ejemplo
a continuación:
@@ -131,9 +131,9 @@ export default {
<>
Puedes registrar un input sin una{" "}
- referencia. De hecho, puedes setear el valor
+ referencia. De hecho, puedes configurar el valor
manualmente con setValue, setError y
- triggerValidation.
+ trigger.
Nota: Debido a que la{" "}
@@ -270,11 +270,11 @@ export default {
renderizado mínimo
renderizado de acuerdo a cambios de estado locales, mientras
- tipeas en el input.
+ escribes en el input.
renderizado de acuerdo a cambios en librerías de
- administración de estado (Redux), mientras tipeas en el
+ administración de estado (Redux), mientras escribes en el
input.
@@ -378,14 +378,14 @@ export default {
cada cambio en los input y asignar la propiedad value.
- Alternativamente, puedes utilizar nuestro componente wrapper{" "}
+ De formar alterna, puedes utilizar nuestro componente wrapper{" "}
Controller
{" "}
- el que se encargará de realizar el registro por ti.
+ es el encargado de realizar el registro por ti.
- watch: suscríbase a
- cambio de entrada a través del detector de eventos y renderizado
- en función de qué campos que están suscritos. Renderizar en
- función de qué entrada es visto / suscrito revisa{" "}
+ watch: puede
+ suscríbirse a cambios en entradas a través del detector de
+ eventos y renderizado en función de los campos suscritos.
+ Renderizar en función de qué entrada es vista / suscrito revisa{" "}
>
),
},
+ {
+ title: "How to work with modal or tab forms?",
+ description: (
+ <>
+
+ Es importante entender que React Hook Form abraza la forma nativa
+ comportamiento por estado de entrada de la tienda dentro de cada
+ entrada (excepto personalizado
+ registrarse en useEffect). Uno de los
+ comunes conceptos erróneos es cuando se trabaja con formularios
+ modales o tabuladores, al montar y desmontando la forma / entradas
+ que permanecerá el estado de las entradas. Eso es implementación
+ incorrecta, en cambio, la solución correcta siempre debe
+ construyendo un nuevo formulario para su formulario dentro de modal
+ o cada pestaña y capturar sus datos de envío en estado local o
+ global.
+
+ >
+ ),
+ },
],
}
diff --git a/src/data/es/getStarted.tsx b/src/data/es/getStarted.tsx
index f5b0ae269..90f7ce703 100644
--- a/src/data/es/getStarted.tsx
+++ b/src/data/es/getStarted.tsx
@@ -3,7 +3,10 @@ import code from "../../components/codeExamples/defaultExample"
import { Link } from "@reach/router"
import translateLink from "../../components/logic/translateLink"
import CodeArea from "../../components/CodeArea"
-import { uiLibraryHookInput } from "../../components/codeExamples/getStarted"
+import {
+ uiLibraryHookInput,
+ uiLibraryHookInputTs,
+} from "../../components/codeExamples/getStarted"
import typographyStyles from "../../styles/typography.module.css"
export default {
@@ -178,7 +181,12 @@ export default {
Controller, cuando utilizas este
componente, él se encarga de realizar el proceso de registro por ti.
-
+
Opción 3: Por último, puedes
configurar un registro personalizado utilizando el hook{" "}
@@ -227,11 +235,64 @@ export default {
+ React Hook Form soporta validación de formularios basada en esquemas
+ con{" "}
+
+ Yup
+
+ ,{" "}
+
+ Superstruct
+ {" "}
+ &{" "}
+
+ Joi
+
+ , donde puedes pasar tu validationSchema a{" "}
+ useForm como configuración opcional. React
+ Hook Form validará los datos de tus inputs contra el esquema y
+ retornará los errores o el resultado válido
+ según corresponda.
+
+ >
+ ),
+ step1: (
+ <>
+
+ Paso 1: Agregá{" "}
+ Yup en tu proyecto.
+
+ >
+ ),
+ step2: (
+
+ Paso 2:Crea tu esquema de
+ validación y registra los inputs en React Hook Form.
+
+ ),
+ },
errors: {
title: "Manejo de errores",
description: (
<>
- React Hook Form proporciona el objeto errors
+ React Hook Form proporciona el objeto errors
para exponer los errores que hayan en el formulario.
>
),
diff --git a/src/data/es/migrateV5ToV6.tsx b/src/data/es/migrateV5ToV6.tsx
new file mode 100644
index 000000000..3b7fb8a2a
--- /dev/null
+++ b/src/data/es/migrateV5ToV6.tsx
@@ -0,0 +1,280 @@
+import CodeArea from "../../components/CodeArea"
+import validationSchema from "../../components/codeExamples/validationSchema"
+import * as React from "react"
+import typographyStyles from "../../styles/typography.module.css"
+
+export default (
+ <>
+
Hola,
+
+ Estos son los cambios importantes que necesitaría ajustar. Esperamos
+ sinceramente esos cambios no están creando demasiados problemas para su
+ base de código. Si tu se preguntan algunos de los fundamentos, puede echar
+ un vistazo a este {""}
+
+ solicitud de extracción
+ {" "}
+ para más detalles.
+
+
+
+ ❤️ React hook Form Team
+
+
+
+
+
+
+
+
useForm:
+
+
+
+ Estamos eliminando el prefijo validation para toda la
+ configuración.
+
+
+
+
+
+
+
validationSchema:
+
+
+ validationSchema ha sido reemplazado por el estándar {""}
+ resolver, y puede usar Yup, Joi y Superstruct en el
+ momento. Tenemos una biblioteca oficial de resolución para soportar más
+ esquemas validación en el futuro.
+
+
+
+ npm install @hookform/resolvers
+
+
+
+
+
+
Controller:
+
+
+ Hicimos la API de Controller mucho más simple, y lo
+ siguiente Se han eliminado los accesorios y se han reemplazado con
+ accesorios render.
+
+ Este tipo es útil cuando está utilizando el consumidor de contexto en
+ lugar de useFormContext hook.
+
+ ),
+ },
+}
diff --git a/src/data/faq.tsx b/src/data/faq.tsx
deleted file mode 100644
index d0027e76b..000000000
--- a/src/data/faq.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-import faqEn from "../data/en/faq"
-import faqEs from "../data/es/faq"
-import faqPt from "../data/pt/faq"
-import faqZh from "../data/zh/faq"
-import faqJp from "../data/jp/faq"
-import faqKr from "../data/kr/faq"
-import faqRu from "../data/ru/faq"
-
-export default {
- en: faqEn,
- es: faqEs,
- pt: faqPt,
- kr: faqKr,
- jp: faqJp,
- zh: faqZh,
- ru: faqRu,
-}
diff --git a/src/data/generic.tsx b/src/data/generic.tsx
index d29c48319..602f41936 100644
--- a/src/data/generic.tsx
+++ b/src/data/generic.tsx
@@ -1,3 +1,5 @@
+import * as React from "react"
+
export default {
copy: {
en: "Copy",
@@ -334,4 +336,49 @@ export default {
zh: "现场演示",
ru: "Живой пример",
},
+ control: {
+ en: (
+ <>
+ control object is from invoking useForm. it's
+ optional if you are using FormContext.
+ >
+ ),
+ es: (
+ <>
+ El objeto control es obtenido al invocar{" "}
+ useForm.
+ >
+ ),
+ pt: (
+ <>
+ control objeto é invocado do useForm. é
+ opcional, se estiver usando o FormContext.
+ >
+ ),
+ kr: (
+ <>
+ control 객체는 useForm 을 호출하여 나온 것을
+ 넣어주면 됩니다. FormContext 를 사용하고 있다면 필수는 아닙니다.
+ >
+ ),
+ jp: (
+ <>
+ control オブジェクトは useForm{" "}
+ から呼び出されます。 ただし、 FormContext
+ を使用している場合は省略できます。
+ >
+ ),
+ zh: (
+ <>
+ control对象来自调用useForm的对象。
+ 如果您使用的是FormContext,则为可选。
+ >
+ ),
+ ru: (
+ <>
+ control объект - это вызов формой useForm. Это
+ необязательно, если вы используете FormContext.
+ >
+ ),
+ },
}
diff --git a/src/data/getStarted.tsx b/src/data/getStarted.tsx
deleted file mode 100644
index 6b6946798..000000000
--- a/src/data/getStarted.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-import getStartedEn from "../data/en/getStarted"
-import getStartedEs from "../data/es/getStarted"
-import getStartedPt from "../data/pt/getStarted"
-import getStartedZh from "../data/zh/getStarted"
-import getStartedJp from "../data/jp/getStarted"
-import getStartedKr from "../data/kr/getStarted"
-import getStartedRu from "../data/ru/getStarted"
-
-export default {
- en: getStartedEn,
- es: getStartedEs,
- pt: getStartedPt,
- kr: getStartedKr,
- jp: getStartedJp,
- zh: getStartedZh,
- ru: getStartedRu,
-}
diff --git a/src/data/home.tsx b/src/data/home.tsx
index 633aabfc0..ae34ba7c1 100644
--- a/src/data/home.tsx
+++ b/src/data/home.tsx
@@ -15,7 +15,7 @@ export default {
en: "React hook for form validation without the hassle",
es: "React hook para validación de formularios sin molestias",
pt: "React hook para validação de formulário sem aborrecimento",
- kr: "번거로움 없이 폼 검증을 위한 React hook",
+ kr: "번거로움 없는 폼 검증을 위한 React hook",
jp: "手間がかからないフォームバリデーションのための React フック",
zh: "React hook用于表单验证,无需麻烦",
ru: "React hook для валидации форм без хлопот",
@@ -304,12 +304,12 @@ export default {
<>
작성하는 코드 양을 줄이는 것은 React Hook Form의 주요 목표 중
- 하나입니다. 이를 설명하기 위해 가장 인기있는 폼 유효성 검사
- 라이브러리들을 사용한 간단한 폼을 살펴보세요.
+ 하나입니다. 인기있는 폼 유효성 검사 라이브러리와 아주 간단한 비교를
+ 해 보겠습니다.
- ⚠ 참고:아래의 Formik 및
- Redux-Form 코드는 다음과 같습니다. 공식 문서에서 복사。
+ ⚠ 참고: 아래의 Formik 및
+ Redux-Form 공식 문서에서 가져온 것입니다.
>
),
@@ -382,13 +382,13 @@ export default {
),
},
es: {
- title: "Isolate Component Re-render",
+ title: "Aislar el Re-render de un componente",
description: (
<>
- You have the ability to isolate components re-render which lead to
- less performance impact on your page or app. The following example
- demonstrate such behaviour.
+ Tú tienes la habilidad de aislar el re-render de un componente lo
+ que conducirá a un menor impacto en el rendimiento de tu aplicación
+ o sitio web. El siguiente ejemplo lo demuestra.
@@ -421,7 +421,7 @@ export default {
<>
페이지나 앱의 퍼포먼스에 부정적인 영향을 줄 수 있는 리랜더링을
- 분리할 수 있습니다. 아래의 예제는 그 방법을 보여줍니다.
+ 분리할 수 있습니다. 아래의 예제는 그 차이를 보여줍니다.
+ Performance is an important aspect of user experience in terms of
+ building forms. You will have the ability to subscribe to individual
+ input change without re-render the entire form.
+
+ Performance is an important aspect of user experience in terms of
+ building forms. You will have the ability to subscribe to individual
+ input change without re-render the entire form.
+
+ Performance is an important aspect of user experience in terms of
+ building forms. You will have the ability to subscribe to individual
+ input change without re-render the entire form.
+
+ Performance is an important aspect of user experience in terms of
+ building forms. You will have the ability to subscribe to individual
+ input change without re-render the entire form.
+
+ Performance is an important aspect of user experience in terms of
+ building forms. You will have the ability to subscribe to individual
+ input change without re-render the entire form.
+
@@ -460,26 +460,24 @@ export default {
),
},
- // todo: jp translation please
{
- title:
- "Why is default value not changing correctly with ternary operator?",
+ title: "なぜデフォルト値は三項演算子で正しく変更されないのですか?",
description: (
<>
- React Hook Form doesn't control your entire form and inputs, which
- is the reason why React wouldn't recognise the actual input that has
- been exchanged or swopped. As a solution, you can resolve this
- problem by giving a unique key prop to your input. You
- can also read more about the key props from{" "}
+ React Hook Form はフォーム全体と全ての input
+ 要素を制御しません。理由は、React が入れ替えられた input
+ 要素を認識しないからです。 解決策として、input 要素に一意な{" "}
+ key props を渡すことでこの問題を解決できます。key props
+ について{" "}
this article written by Kent C. Dodds
-
- .
+ {" "}
+ から詳しく読むことができます。
- After a validation error, React Hook Form will automatically focus
- on the invalids elements of which have their proper ref, like the
- native inputs (eg: {``}) or some 3rd party
- Components that correctly export his ref (eg: from MUI{" "}
+ バリデーションエラーのあと、React Hook Form はネイティブの input
+ 要素(例: {``}) または正しく ref
+ が公開されているいくつかのサードパーティコンポーネント(例: MUI の{" "}
{``}
- )
+ )のような適切な ref を持つ無効な要素に自動でフォーカスを当てます。
- However, for some 3rd party controlled Components like{" "}
- {``} from MUI or {``}{" "}
- from AntD) it's very difficult to predict his ref because the
- formats changes, so React Hook Form will properly detect the
- validation error but will not be able to automatically focus that
- kind of Components.
+ しかし、いくつかの(MUI の {``} や AntD
+ の {``}のような)
+ サードパーティ制御コンポーネントでは、フォーマットが変更されるため
+ ref を予見することはとても難しいです。 そのため、React Hook Form
+ はバリデーションエラーを正しく見つけますがほとんどのコンポーネントに自動でフォーカスを当てることができません。
- As a workaround, after the validation error, you can manually focus
- on the 3rd party controlled Component (if you can get the actual
- internal input ref), for example:
+ 回避策として、(もし実際の内部の input 要素の ref
+ を取得できるなら)バリデーションエラーの後に、
+ 手動でサードパーティ制御コンポーネントにフォーカスを当てることができます。例えば:
- If you find difficult to make the autofocus with external controlled
- component. It is possible to disable the "autofocus on error"
- feature. Maybe this behavior will bring a better user experience in
- some cases. {`useForm({submitFocusError: false});`}
+ もし外部の制御コンポーネントを使って自動でフォーカスを当てることが難しいと感じるなら、
+ 「エラー時の自動フォーカス」機能を無効にすることが可能です。おそらくこの機能は
+ いくつかのケースでより良いユーザー体験をもたらします。
+ {`useForm({shouldFocusError: false});`}
+ ),
+ },
+}
diff --git a/src/data/kr/advanced.tsx b/src/data/kr/advanced.tsx
index 3e12d9a59..a68eb9fa7 100644
--- a/src/data/kr/advanced.tsx
+++ b/src/data/kr/advanced.tsx
@@ -4,6 +4,7 @@ import CodeArea from "../../components/CodeArea"
import accessibleCodeBase from "../../components/codeExamples/accessibleCodeBase"
import accessibleCodeFinal from "../../components/codeExamples/accessibleCodeFinal"
import { step1, step2, step3 } from "../../components/codeExamples/formWizard"
+import * as CodeExampleTestingForm from "../../components/codeExamples/testingForm"
import smartForm from "../../components/codeExamples/smartForm"
import form from "../../components/codeExamples/form"
import input from "../../components/codeExamples/input"
@@ -50,19 +51,38 @@ export default {
title: "에러 메세지",
description: (
- 에러 메세지는 입력값에 관하여 문제가 있을 때 사용자에게 시각적으로
- 피드백을 주는 것입니다. React Hook Form 은 쉽게 에러를 되짚을 수 있도록
- 에러 객체를 제공합니다. 하지만 더 나은 방식으로 에러를 스크린에
- 랜더링하기 위해 몇 가지 다른 방법이 있습니다.
+ 에러 메세지는 입력값에 관하여 문제가 있을 때 사용자에게 시각적인
+ 피드백을 줍니다. React Hook Form 은 쉽게 에러를 되짚을 수 있도록 에러
+ 객체를 제공합니다. 하지만 더 나은 방식으로 에러를 스크린에 랜더링하기
+ 위해 몇 가지 다른 방법이 있습니다.
),
register: (
<>
register 하면서 에러 메세지를 심어보세요. 쉽게{" "}
- value 속성에 에러 메세지를 넣을 수 있습니다. 예:
+ value 속성에 에러 메세지를 넣을 수 있습니다.
>
),
component: "에러 출력을 돕기 위해 ErrorMessage 컴포넌트를 만들어보세요.",
+ optionalChaining: (
+ <>
+
+
+ 옵셔널 체이닝
+ {" "}
+ 접근자 ?. 는 errors 객체를 읽을 때{" "}
+ null 이나 undefined 인 속성 때문에 에러가
+ 발생할 걱정을 하지 않고 객체의 속성에 접근할 수 있습니다.
+
-
- 옵셔널 체이닝
- {" "}
- 접근자 ?. 는 errors 객체를 읽을 때{" "}
- null 이나 undefined 인 속성 때문에 에러가
- 발생할 걱정을 하지 않고 속성에 접근할 수 있습니다.
-
-
- {`errors?.firstName?.message`}
-
- >
- ),
},
accessibility: {
title: "접근성 (A11y)",
@@ -131,8 +132,8 @@ export default {
target="_blank"
>
ARIA
-
- 를 활용하여 향상된 접근성을 제공합니다.
+ {" "}
+ 속성을 활용하여 향상된 접근성을 제공합니다.
@@ -193,7 +194,7 @@ export default {
3단계: 스토어에 모아진 모든
- 데이터를 사용하여 마지막 폼을 제출하거나 결과물을 출력하세요.
+ 데이터를 사용하여 최종 폼을 제출하거나 결과물을 출력하세요.
각각의 컴포넌트가 어떻게 이루어져 있는지 살펴보겠습니다.
-
+
Form
-
+
Form 컴포넌트가 하는 일은 모든{" "}
@@ -240,9 +241,9 @@ export default {
url="https://codesandbox.io/s/react-hook-form-smart-form-component-eqb3n"
/>
-
+
Input / Select
-
+
인풋 컴포넌트의 역할은 자기 자신을 react-hook-form 에
@@ -266,16 +267,16 @@ export default {
description: (
<>
- 이 기능은 React Hook Form 이 제공하는 제일 좋은 기능 중 하나입니다. 이
- 기능을 구현하기 위해 (다른 라이브러리같은) 컴포넌트를 불러오는 대신에
- 이미 있는 HTML 마크업을 활용할 수 있습니다. 핵심은 그 안에 있는{" "}
+ 이 기능은 React Hook Form 이 제공하는 제일 유용한 기능 중 하나입니다.
+ 이 기능을 구현하기 위해 (다른 라이브러리 등의) 컴포넌트를 불러오는
+ 대신에 이미 있는 HTML 마크업을 활용할 수 있습니다. 핵심은 그 안에 있는{" "}
name 속성입니다. React Hook Form 에서는 name{" "}
- 속성이 여러분이 사용하고자 하는 자료 구조를 대변합니다.
+ 속성이 여러분이 사용하고자 하는 자료 구조를 반영합니다.
- Note: we have also build a
- custom hook for complex scenario:{" "}
+ 참고: 더 복잡한 시나리오에
+ 대응하기 위한 커스텀 훅도 있습니다:{" "}
useFieldArray.
@@ -285,64 +286,32 @@ export default {
- Note: if your application
- requires functionality such as: Delete, Insert, Append, Preprend. Here
- is the{" "}
+ 참고: 여러분의 애플리케이션이
+ 삭제, 삽입, 앞에 붙이기(Prepend), 뒤에 붙이기(Append)를 지원해야
+ 한다면 Controller 로
+ 만들어진{" "}
- link for such implementation.
+ 구현체를 확인해보세요.
{" "}
- with Controller.
- React Hook Form 은{" "}
-
- Yup
-
- 을 활용하여 스키마 기반의 폼 유효성 검사를 제공합니다.{" "}
- validationSchema 를 useForm 에
- 넘겨주어 추가 설정을 할 수 있습니다. React Hook Form 은 입력된
- 데이터를 스키마와 비교하여 에러 혹은 알맞은
- 결과를 표시합니다.
-
- >
- ),
- step1: (
- <>
-
- 1단계:Yup 을
- 프로젝트에 설치합니다.
-
- >
- ),
- step2: (
-
- 2단계: 유효성 검사를 위한
- 스키마를 작성하고 React Hook Form 을 사용하여 인풋을 등록합니다.
-
- 폼을 만들 때, 인풋이 아주 깊게 중첩된 컴포넌트 트리 안에 남아있어야 하는
- 때가 있습니다. 그럴 때 FormContext 가
- 아주 유용합니다. 하지만 ConnectForm 을 만들고 리액트의{" "}
+ 폼을 만들 때, 인풋이 아주 깊게 중첩된 컴포넌트 트리 안에 있어야 할 때가
+ 있습니다. 그럴 때 FormContext 가 아주
+ 유용합니다. 하지만 ConnectForm 을 만들어 리액트의{" "}
renderProps{" "}
패턴을 활용하여 개발자 경험을 향상시킬 수 있습니다. 이러한 컴포넌트를
- 사용할 때의 이점은 어디서나 인풋을 React Hook Form과 연결할 수 있다는
- 것입니다.
+ 만들어 사용할 때의 이점은 어디서나 인풋을 React Hook Form과 연결할 수
+ 있다는 것입니다.
),
},
@@ -361,16 +330,16 @@ export default {
>
여기 예제가 있습니다.
{" "}
- 하지만 이러한 동작은 제어 컴포넌트에는 적용하기 어려운데,{" "}
+ 하지만 이 작동방식은 제어 컴포넌트에는 잘 작동하지 않는데,{" "}
ref 가 등록되어있지 않기 때문입니다. 이럴 때는 아래의
방법을 사용할 수 있습니다.
-
- Controller 를 불러와서
- 컴포넌트를 감싸면 알아서 register 와 unregister 처리를 합니다.
-
+
인풋을 활성 상태를 토글하기
+
+
+
모달과 팝업 폼을 위한 별도의 폼을 만들기
@@ -383,7 +352,13 @@ export default {
useEffect
- 를 활용할 수 있습니다.
+ 를 활용하여 커스텀 등록을 구현하기
+
+
+
+
+ Controller 를 불러와서
+ 컴포넌트를 감싸면 알아서 register 와 unregister 처리하기
@@ -423,11 +398,17 @@ export default {
- 메모이즈 된 유효성 검사 스키마(혹은 컴포펀트 바깥에 선언하여
- 의존성이 생기지 않도록)를 정의하세요
+
+ 메모이즈 된 유효성 검사 스키마(혹은 컴포펀트 바깥에 선언하여
+ 의존성이 생기지 않도록)를 정의하기
+
+ 테스트는 아주 중요합니다. 코드에서 발생하는 버그나 실수를 줄이고,
+ 코드베이스를 리팩토링 할 때 안정성을 보장하기 때문입니다.
+
+
+
+ 우리는{" "}
+
+ testing-library
+ {" "}
+ 사용을 권장합니다. 단순하고 사용자 행동에 더 초점을 맞추어 테스트를
+ 작성할 수 있기 때문입니다.
+
+
+
♦
+
+
+ 1단계: 테스트 환경을
+ 설정합니다.
+
+
+
+ mutationobserver-shim을 설치하세요. react-hook-form 은
+ MutationObserver를 사용하여 인풋이 DOM 으로부터 언마운트
+ 되었는지 감지하기 때문입니다.
+
+
+
+
+
+ setup.js 파일을 만들어 mutationobserver-shim{" "}
+ 를 가져옵니다.
+
+
+
+
+ 마지막으로 jest.config.js 파일에서 setup.js{" "}
+ 를 가져오도록 설정합니다.
+
+
+
+
+
+ 2단계: 로그인 폼을
+ 작성해봅시다.
+
+
+
+ 폼에 맞는 role 속성을 설정했습니다. 이 속성들은 테스트를 작성할 때와
+ 접근성을 향상시킬 때 도움이됩니다. 더 자세한 정보는{" "}
+
+ testing-library
+ {" "}
+ 의 문서를 확인하세요.
+
+
+
+
+
+ 3단계: 테스트를 작성합니다.
+
+
+
테스트를 작성할 때 아래의 기준을 따릅니다.
+
+
+
+
실패하는 테스트를 작성해봅니다.
+
+
+ waitFor 및 find* 메소드를 사용하여 폼이
+ 제출되는 것을 감지합니다. handleSubmit 메서드는
+ 비동기적으로 실행되기 때문입니다.
+
+
+
+
각 인풋에 대응하는 유효성 검사를 테스트합니다.
+
+
+ *ByRole 메서드를 사용하여 각기 다른 엘리먼트를
+ 가져옵니다. 사용자가 실제로 이런 방식으로 여러분의 UI 컴포넌트를
+ 인지하기 때문입니다.
+
+
+
+
성공하는 테스트를 실행시켜봅니다.
+
+
+
+
+ >
+ ),
+ },
}
diff --git a/src/data/kr/api.tsx b/src/data/kr/api.tsx
index d1b5fc513..e377287d2 100644
--- a/src/data/kr/api.tsx
+++ b/src/data/kr/api.tsx
@@ -1,25 +1,46 @@
import * as React from "react"
import colors from "../../styles/colors"
-import Popup from "../../components/Popup"
-import generic from "../generic"
-import CodeArea from "../../components/CodeArea"
+import CodeArea, { CodeSandBoxLink } from "../../components/CodeArea"
import useFieldArrayArgument from "../../components/codeExamples/useFieldArrayArgument"
+import generic from "../generic"
import typographyStyles from "../../styles/typography.module.css"
import buttonStyles from "../../styles/button.module.css"
-import code from "../../components/codeExamples/defaultExample"
+import tableStyles from "../../styles/table.module.css"
export default {
title: "API 설명서",
header: {
- description: "은 API 단순화를 통해 최고의 DX를 제공합니다.",
+ description:
+ "단순화된 API 를 통해 최고의 DX 를 제공하는데 초점을 맞추었습니다.",
},
useForm: {
title: "useForm",
intro: (
<>
- useForm 을 호출하여 다음의 메소드들을 사용할 수 있습니다..{" "}
+ useForm 을 호출하여 다음의 메소드들을 사용할 수 있습니다.{" "}
>
),
+ description: (
+
+ useForm 에서는 옵셔널한 인자도 있습니다. 아래의
+ 예제는 모든 옵션의 기본값을 보여줍니다.
+
+ ),
+ validateCriteriaMode: (
+
+
+
+ firstError(기본값) 으로 설정한 경우, 각 필드의 첫 번째
+ 에러만 수집됩니다.
+
- 이 옵션을 true 로 설정하면 브라우저의 기본 유효성 검사가
- 활성화됩니다.
- {" "}
-
- 브라우저 기본 유효성 검사
-
- 에 대한 내용을 확인하시고 좀 더 자세한 내용과 예시는{" "}
- goToSection("nativeValidation")}
- >
- nativeValidation
- {" "}
- 에서 참고하실 수 있습니다.
+ 기본적으로 입력이 제거되면 React Hook Form 은{" "}
+ MutationObserver 를 사용하여 언마운트 된 입력을 감지하고{" "}
+ unregister 합니다. 그러나 언마운트 할 때 입력 상태가
+ 손실되지 않도록 shouldUnregister 를 false 로
+ 설정할 수 있습니다.
- 이 함수로 단일 입력 혹은 여러 입력들을 unregister 할 수
- 있습니다. 이 함수는 useEffect 로 입력을 등록한 뒤,
- 컴포넌트가 언마운트 되면서 등록을 해제하고자 할 때 유용합니다.
+ 이 함수로 단일 입력 혹은 배열로 지정된 여러 입력들을{" "}
+ unregister 할 수 있습니다.
- 이 함수에서 입력/선택(input/select) Ref 와 유효성 검사
- 규칙을 등록(register)할 수 있습니다.
+ 이 함수에서 입력/선택(input/select) Ref 를 등록하고,
+ React Hook Form 을 통한 유효성 검사를 적용할 수 있습니다.
- 유효성 검사 규칙은 모두 HTML 표준을 기반으로 하며, 커스텀 유효성
- 검사도 가능합니다.
+ 유효성 검사 규칙은 모두 HTML 표준을 기반으로 하며, 커스텀 유효성 검사
+ 규칙을 적용할 수 있습니다.
중요:name은{" "}
- 필수이며 유니크
- 해야합니다. name은 점(dot)과 괄호 구문도 지원하므로, 중첩 된 폼 필드를
- 쉽게 만들 수 있습니다. 예제는 다음과 같습니다.
+ 필수이며 단일값(unique)이어야 합니다. 인풋의 name은
+ 점(dot)과 괄호 구문도 지원하므로, 중첩 된 폼 필드를 쉽게 만들 수
+ 있습니다. 예제는 다음과 같습니다.
>
),
@@ -246,16 +254,17 @@ export default {
borderLeft: `4px solid ${colors.lightPink}`,
}}
>
- arrays/array 필드의 경우, name[index] 와 같이
- name을 지정할 수 있습니다.{" "}
+ 간단한 배열 필드(Array Fields)를 다루고 있다면, 인풋 이름을{" "}
+ name[index] 형태로 지정할 수 있습니다.
- Field Array 예제를 확인하세요.
+ 여기서 배열 필드 예제를 확인하세요
- .
+ . 더 복잡한 로직을 구현해야 한다면, useFieldArray 단락을
+ 확인해보세요.
),
example: "제출 결과",
@@ -263,11 +272,12 @@ export default {
"등록 옵션(Register Options)을 선택하면, 아래의 API 테이블이 업데이트됩니다.",
options: {
title: "Register Options",
- registerWithValidation: "유효성 검사와 함께 등록",
- registerWithValidationMessage: "유효성 검사 및 에러 메시지 등록",
+ registerWithValidation: "유효성 검사 규칙을 지정하면서 등록할 경우",
+ registerWithValidationMessage:
+ "유효성 검사 규칙 및 에러 메시지를 지정하면서 등록할 경우",
note: (goToSection) => (
<>
-
Custom Register
+
커스텀 등록
커스텀 컴포넌트와 Ref에 액세스 할 수 없는 경우, 입력을
수동으로 등록 할 수 있습니다. 이는 실제로 React Native 또는{" "}
@@ -278,7 +288,15 @@ export default {
>
react-select
{" "}
- 와 같은 커스텀 컴포넌트와 작업할 때 사용될 수 있습니다.
+ 와 같은 커스텀 컴포넌트와 작업할 때 사용될 수 있습니다. 또한 이
+ 작업을 대신 처리해주는{" "}
+ goToSection("Controller")}
+ >
+ Controller
+ {" "}
+ 컴포넌트를 제공하고 있습니다.
@@ -311,9 +329,9 @@ export default {
- Nota: multiple radio inputs
- with the same name, you want to register the validation to the last
- input so the hook understand validate them as a group at the end.
+ 참고: 같은 이름을 가진
+ 여러개의 라디오 인풋에는 유효성 검사를 마지막 인풋에 등록해야 훅이
+ 하나의 그룹으로 인지하여 검사를 실행합니다.
>
),
@@ -356,77 +374,94 @@ export default {
>
),
- dirty: "사용자가 어떠한 입력이라도 했다면, true로 설정하십시오.",
- dirtyFields: "고유 한 사용자 수정 필드 세트.",
- isSubmitted:
- "사용자가 폼을 제출 한 후 true로 설정하십시오. 양식을 제출 한 후 reset 메소드로 호출 될 때까지 해당 상태가 제출 된 상태로 유지됩니다.",
- touched: "상호 작용된 모든 입력의 배열입니다.",
+ isDirty: (
+ <>
+ 사용자가 어떤 인풋이라도 수정했다면 true 가 됩니다.
+
+ 참고: 파일 타입의 인풋은
+ 애플리케이션 계층에서 관리가 되어야 합니다. 파일 선택을 취소할 수도
+ 있고{" "}
+
+ FileList
+ {" "}
+ 객체도 있기 때문입니다.
+
+ >
+ ),
+ isSubmitted: (
+ <>
+ 사용자가 폼을 제출하고 나면 true 가 됩니다.{" "}
+ reset 메서드가 호출될 때까지 이 상태는 유지됩니다.
+ >
+ ),
+ dirtyFields: "사용자가 수정한 필드들이 기록된 객체입니다.",
+ touched: "사용자가 건드렸던 모든 인풋을 가지고 있는 객체입니다.",
isSubmitting: (
<>
- 폼 제출하는 동안은 true 로, 그 후에는 false로
- 설정합니다.
+ 폼 제출하는 동안은 true 로, 그 후에는 false 가
+ 됩니다.
+ >
+ ),
+ submitCount: "폼을 제출한 횟수",
+ isValid: (
+ <>
+ 에러가 없다면 true 가 됩니다.
>
),
- submitCount: "제출 한 폼의 수",
- isValid: "에러가 없다면, true로 설정하세요.",
},
errors: {
title: "errors",
description: (currentLanguage) => (
<>
-
각 입력에 대한 폼 에러 혹은 에러 메시지를 가진 객체입니다.
{" "}
-
-
- {generic.note[currentLanguage]}:
- {" "}
- V3 과 V4 의 차이점:
-
-
-
-
V4: 중첩된 객체
-
- 사용 이유: 옵셔널 체이닝이 커뮤니티 사이에서 많이
- 알려졌고, 더 나은 타입 지원을 합니다.
-
-
- {`errors?.yourDetail?.firstName;`}
-
-
-
-
V3: 평탄한 객체
-
- 사용 이유: 단순하고 에러에 접근하기 쉽습니다.
-
-
- {`errors['yourDetail.firstName'];`}
-
-
-
+
각 인풋에 대응되는 폼 에러 혹은 에러 메시지를 가진 객체입니다.
{" "}
>
),
types: (
<>
- 여러 종류의 에러가 하나의 필드에 적용되어야 하는 비밀번호 규칙 같은
- 입력의 유효성 검사를 할 때 유용합니다. 이 기능을 활성화하려면,{" "}
- validateCriteriaMode: 'all' 으로 설정해두는 것을 잊지
- 마세요.
+
+ 하나의 인풋에서 발생할 수 있는 모든 에러를 리턴하려 할 때 유용합니다.
+ 예를 들어, 최소 길이를 충족하면서 특수 문자를 포함해야 하는 패스워드
+ 필드를 검사할 때가 있습니다.
+
+
+ 참고: 이 옵션을 사용하기
+ 위해서 validateCriteriaMode 옵션을 all 로
+ 설정해야 합니다.
+
>
),
message: `메시지는 기본적으로 빈 문자열입니다. 하지만 에러 메시지와 함께 유효성 검사를 함께 등록하면, 이 값이 반환됩니다.`,
ref: `입력 엘레먼트에 대한 ref`,
+ note: (goToSection) => (
+
+ 참고: {" "}
+ goToSection("ErrorMessage")}
+ >
+ ErrorMessage
+ {" "}
+ 를 사용하여 오류 상태를 처리 할 수 있습니다.
+
- 이 함수는 폼 내의 필드 값과 에러를 재설정(reset) 합니다.{" "}
- omitResetState 를 제공하면 자유롭게 특정 상태 만
- 재설정합니다. values를 옵셔널 인수로 전달하면 폼의 기본
- 값으로 재설정 할 수 있습니다.
+ 이 함수는 폼 안의 필드 값과 에러를 초기화(reset) 합니다.{" "}
+ omitResetState를 사용하면 자유롭게 특정 상태만 초기화할
+ 수 있습니다. 부가적으로 values 를 전달하면 이 값을
+ 초기화되는 폼의 기본 값으로 재설정 할 수 있습니다.
참고:{" "}
@@ -517,10 +551,10 @@ export default {
을 사용하여 제어 컴포넌트를 감싸 처리할 수 있습니다.
- 참고: 당신은해야합니다
- useForm 또는중 defaultValues 제공
- 컨트롤러 를 재설정하기위한 값으로 재설정
- 구성 요소의 가치.
+ 참고:Controller{" "}
+ 컴포넌트의 값을 재설정하려면
+ useForm 호출 시 defaultValues 를
+ 지정해주어야 합니다.
>
),
@@ -533,17 +567,32 @@ export default {
이 함수를 사용하면 한개 혹은 그 이상의 입력값 에러를 수동으로 설정할
수 있습니다.
-
- 참고 :이 방법은 오류와 차단을
- 지속하지 않습니다 제출 조치. handleSubmit 함수 중에 더
- 유용합니다. 비동기 유효성 검사 후 사용자에게 오류 피드백을
- 제공하려고합니다.
-
+
+
+
+ 이 메서드는 인풋과 연관된 에러인 경우 유효성 검사를 통과하면 에러
+ 값을 유지하지 않습니다.
+
+
+
+
+ 인풋 필드와 연관되지 않은 에러를 지정한 경우 에러 값이 유지됩니다.
+ 이 경우 반드시 clearError를 사용하여 수동으로
+ 제거해야합니다.
+
+
+
+
+ handleSubmit 안에서 비동기적으로 유효성 검사를 수행한
+ 뒤 사용자에게 에러 피드백을 제공할 때 유용합니다.
+
- 이 함수를 통해 동적으로 입력/선택 값을 설정할 수 있습니다. 그와
+ 이 함수를 통해 동적으로 인풋/셀렉트 값을 설정할 수 있습니다. 그와
동시에, 아래의 조건이 충족할 때만 다시 랜더링되어 불필요한 리랜더링을
피하려 합니다.
@@ -582,25 +631,30 @@ export default {
- 맨 처음 실행되어 폼이 dirty 상태가 되도록 했을 때
-
-
-
-
- formState 를 touched 로 업데이트 했을 때
+ 맨 처음 실행되어 폼의 isDirty 상태가{" "}
+ true 가 되었을 때
- 참고: 이 함수를 호출함으로써,{" "}
- formState는 이 입력의 name을{" "}
- touched로 설정하게 됩니다.
+ shouldValidate를 true로 설정하여, 필드
+ 유효성 검사를 트리거할 수 도 있습니다.
+
+
+
- shouldValidate를 true로 설정하여, 필드
- 유효성 검사를 트리거할 수 도 있습니다. 예 :{" "}
- setValue('name', 'value', true)
+ 필드를 건드려진 상태(dirty)로 설정하기 위해 shouldDirty{" "}
+ 옵션을 true로 설정할 수도 있습니다.
- 이 함수는 전체 폼 데이터를 반환하는 함수이며, 폼 내 값을 검색하려는
- 경우에 유용합니다.
+ 폼의 값을 읽을 때 사용합니다. watch 와 다르게{" "}
+ getValues 는 리랜더링을 일으키거나 입력값의 변화를
+ 구독하지 않는다는 것입니다. 이 함수는 아래의 방식으로 사용합니다.
+
- 기본적으로, getValues()는 폼 데이터를 flat
- structure로 반환합니다. 예 :{" "}
- {`{ test: 'data', test1: 'data1'}`}
+ getValues(): 폼의 전체 값을 읽습니다.
+
+
+
+
+ getValues('test'): 폼 안의 개별 인풋 값을 읽습니다.
+ name.
- 정의된 폼 필드에서 getValues({`{ nest: true }`}) 는{" "}
- name 입력 값에 따라 중첩된 구조의 데이터로
- 반환됩니다. 예 :{" "}
- {`{ test: [1, 2], test1: { data: '23' } }`}
+ getValues(['test', 'test1']): 인풋의{" "}
+ name 속성을 지정하여 여러 값을 읽습니다.
- 외부 스키마와 유효성 검사 규칙을 함께 사용하고 싶을 경우,{" "}
- useForm의 validationSchema를 옵셔널 인자로
- 적용 할 수 있습니다. React Hook Form의 객체 스키마 유효성 검사에서는{" "}
-
- Yup
- {" "}
- 을 지원합니다.
-
+ <>
+
+ 비제어 필드 배열 (동적 입력값) 에 대응하기 위한 커스텀 훅입니다. 이
+ 훅은 더 나은 사용자 경험과 폼 퍼포먼스를 제공하기 위해서 태어났습니다.{" "}
+
+ 이 짧은 비디오를 보고
+ {" "}
+ 제어 vs 비제어 필드 배열을 비교할 수 있습니다.
+
+
+
+
+
+
+
{generic.name.kr}
+
{generic.type.kr}
+
{generic.required.kr}
+
{generic.description.kr}
+
+
+
+
+
+ name
+
+
+ string
+
+
+
연결할 필드 이름
+
+
+
+ control
+
+
+ Object
+
+
+
{generic.control.kr}
+
+
+
+ keyName
+
+
+
+ string = 'id'
+
+
+
+
+ 필드 배열 key 값, 기본값은 "id"입니다. 키 이름을
+ 변경할 수 있습니다.
+
+
+
+
+
+
+
+
+
+ 중요:
+ useFieldArray는 비제어 컴포넌트 기반으로 구성됩니다.
+ 아래의 참고 사항은 폼을 구현하면서 비제어 컴포넌트의 특성 상 유념해야
+ 하는 점을 새겨둘 수 있도록 돕습니다.
+
+
+
+
+
+ useForm hook 에 있는 defaultValues 를
+ 전달하여 fields 를 생성할 수 있습니다.
+
+
+
+
+ fields 객체의 id 값을 컴포넌트의 key 로
+ 전달하는 것을 잊지 마세요.
+
+
+
+
+ fields[index] 에 defaultValue 를
+ 설정하는 것을 잊지 마세요.
+
+
+
+
+ 액션을 연속하여 호출할 수 없습니다. 액션은 매 랜더링마다
+ 수행되어야 합니다.
+
+ {
+ if (fields.length === 2) {
+ remove(0);
+ }
+ append({ test: 'test' });
+}}
+
+// ✅ The following is correct and second action is triggered after next render
+handleChange={() => {
+ append({ test: 'test' });
+}}
+
+React.useEffect(() => {
+ if (fields.length === 2) {
+ remove(0);
+ }
+}, fields)
+ `}
+ />
+
+
+
+ 만약 useFieldArray 를 사용하는 경우, 배열 인풋을
+ 등록할 때 {`ref={register}`} 대신{" "}
+ {`ref={register()}`} 형태로 사용하는 것이 중요합니다.
+ 그래야 register 가 배열의 map 함수
+ 안에서 수행됩니다.
+
+
+
+
+ useEffect 안에서 커스텀 등록을 하거나, 조건부
+ 랜더링을 할 때는 동작하지 않습니다. 조건부 랜더링을 하면서
+ 사용하려면 스타일을 정의하여 보이거나 보이지 않도록(visibility)
+ 토글하고 validate 함수를 사용하여 조건부 유효성
+ 검사를 수행하세요.
+
- register 에 따른 유효성 검사 규칙.
+ control 객체는 useForm 호출 후 리턴된 값
+ 중 하나입니다. 만약 FormContext 를 사용한다면 넣지
+ 않아도 됩니다.
- onChange
+ as
-
- (args: any | EventTarget) => any
-
+ React.ElementType
-
+
- 리턴 값을 커스터마이징 할 수 있습니다, 외부 컴포넌트의{" "}
- value prop 이 어떤 형태를 가지고 있는지 알고 있어야
- 합니다. 이벤트 핸들러에 전달된 값이 object 형태이고{" "}
- type 속성값을 포함하고 있는 경우 value{" "}
- 혹은 checked 속성값을 읽어올 수 있습니다.
+
+ Controller 는 as 로 전달되는 컴포넌트에 onChange,{" "}
+ onBlur 그리고 value props 를 주입합니다.
+
+
+
+ Controller 컴포넌트에 전달되는 모든 prop 은 as 로
+ 전달되는 컴포넌트에도 주입됩니다. 예를 들어 label{" "}
+ prop 을 요구하는 Switch 컴포넌트를 만들었다고 할 때,
+ 이 prop 을 Controller 컴포넌트에 직접 주입하여 여러분이 사용하는
+ 컴포넌트에 전달되도록 할 수 있습니다.
+
- 이 prop 은 특정한 이벤트 이름을 지정하여 그 이벤트의 변화를 바라볼
- 수 있도록 합니다. 예: onChange 이벤트가{" "}
- onTextChange 로 되어있는 경우.
+ 이것은{" "}
+
+ render prop
+ {" "}
+ 입니다. React 엘리먼트를 리턴하는 함수이며, 컴포넌트에 이벤트나 값을
+ 결합할 수 있습니다. 이를 통해 onChange,{" "}
+ onBlur 및 value 같은 표준적인 이름을
+ 사용하지 않는 외부 컴포넌트에 쉽게 적용할 수 있습니다.
+ (
+
+ ))
+/>
+ } />`}
+ />
- onFocus
+ defaultValue
- () => void
+ any
-
+
+ 비제어 컴포넌트의 defaultValue 와 같습니다.{" "}
+ boolean 값이 주어졌을 때는, 체크박스 입력값으로
+ 다루어집니다.
- 유효성 검사 에러가 발생했을 때 이 콜백을 이용하여 특정 인풋으로
- 포커스를 이동시킬 수 있습니다. 이 함수는 포커스만 시킬 수 있다면
- React 및 React-Native 컴포넌트에 모두 적용됩니다.
+ 참고: {" "}
+ defaultValue 를 직접 주입하거나 useForm{" "}
+ 호출할 때 defaultValues 을 넣어주어야 할 것입니다.
- 여기에{" "}
-
- MUI 를 활용한 예제가 있습니다
-
- .
+ 참고: 만약 폼이 기본값과
+ 함께 reset을 호출한다면, 인라인 값으로{" "}
+ defaultValues 를 제공하는 대신 useForm 을 호출할 때{" "}
+ defaultValues 를 제공해주어야 합니다.
- onBlurName
+ rules
- string
+ Object
- 이 prop 은 특정한 이벤트 이름을 지정하여 그 이벤트의 변화를 바라볼
- 수 있도록 합니다. 예: onBlur 이벤트가{" "}
- onTextBlur 로 되어있는 경우.
+ register 를 호출할 때 지정하는 유효성 검사 규칙과 같은
+ 포맷으로 넣어줍니다.
+
- valueName
+ onFocus
- string
+ () => void
-
+
- 이 prop 은 value prop 을 다시 정의하여(Override)
- value prop 을 사용하지 않는 다른 컴포넌트에 사용할 수
- 있습니다. 예: checked, selected 등.
+
+ 유효성 검사 에러가 발생했을 때 이 콜백을 이용하여 특정 인풋으로
+ 포커스를 이동시킬 수 있습니다. 이 함수는 포커스만 시킬 수 있다면
+ React 및 React-Native 컴포넌트에 모두 적용됩니다.
+
- 폼 컨텍스트(Form Context)는 입력들이 컴포넌트 트리에서 깊이 중첩되었을
- 때 생기는 문제를 해결하고, props를 더 깊이 전달하기 위해
- 사용합니다.
-
- ),
- description: (
<>
- FormContext으로 폼을 감싸면, useFormContext:{" "}
- function 이 하위
- 컴포넌트에서 호출 될 수 있습니다.
+ 폼 컨텍스트(Form Context) 에 접근하기 위한 훅 함수입니다.{" "}
+ useFormContext 는 깊게 중첩된 구조에서 컨텍스트를 prop
+ 으로 전달하기 어려울 때 사용합니다.
- 참고:{" "}
- useFormContext 를 통해 모든 useForm 의 hook
- function이 제공됩니다.
+ useFormContext 를 사용하려면 폼 컴포넌트를{" "}
+ FormContext Provider 로 감싸야 합니다.
- 비제어 필드 배열 (동적 입력값) 에 대응하기 위한 커스텀 훅입니다. 이
- 훅은 더 나은 사용자 경험과 폼 퍼포먼스를 제공하기 위해서 태어났습니다.{" "}
+ 이 함수는{" "}
- 이 짧은 비디오를 보고
+ Yup
+
+ ,{" "}
+
+ Joi
+
+ ,{" "}
+
+ Superstruct
{" "}
- 제어 vs 비제어 필드 배열을 비교할 수 있습니다.
+ 등의 외부 유효성 검사 방법들을 실행할 수 있도록 합니다. 실제로, 이
+ 함수의 목적은 단순히 외부 유효성 검사 라이브러리로 Yup 등을 제한된
+ 범위로 지원하는 정도에서 끝나지 않습니다. 우리는 다양한 라이브러리가
+ React Hook Form 과 함께 동작할 수 있도록 지원하려 합니다. 심지어
+ 유효성 검사 로직을 직접 커스터마이징할 수도 있습니다.
-
이 훅은 아래의 객체와 함수를 제공합니다.
+
+ 우리는 공식적으로 Yup, Joi 및 Superstruct를{" "}
+
+ 표준 리졸버
+
+ 로 지원하고 있습니다.
+
-
+
+ npm install @hookform/resolvers
+
- 중요:
- useFieldArray는 비제어 컴포넌트 기반으로 구성됩니다.
- 아래의 참고 사항은 폼을 구현하면서 비제어 컴포넌트의 특성 상 유념해야
- 하는 점을 새겨둘 수 있도록 돕습니다.
+ 커스텀 리졸버를 작성하실 때{" "}
+ 참고 사항:
- useForm hook 에 있는 defaultValues 를
- 전달하여 fields 를 생성할 수 있습니다.
+ 반드시 values 와 errors 객체를 모두
+ 포함하여 리턴시키세요, 그리고 이 객체들의 기본값은 빈 객체{" "}
+ {`{}`} 가 되어야 합니다.
+
-
- fields 객체의 id 값을 컴포넌트의 key 로
- 전달하는 것을 잊지 마세요.
-
+
errors 객체의 키 값은 반드시 인풋과 연결되어야 합니다.
+
- defaultValue를으로 설정하십시오. 기본값을 설정하려는
- 경우 fields[index]
- 입력을 제거하거나 재설정하십시오.
+ context 인수는 가변 객체이므로 매번 리랜더링마다 바뀔
+ 수 있습니다. 따라서 이 함수는 커스텀 훅 안에서 캐싱될 필요가
+ 있습니다.
-
-
- 액션을 연속하여 호출할 수 없습니다. 액션은 매 랜더링마다
- 수행되어야 합니다.
-
- {
- if (fields.length === 2) {
- remove(0);
- }
- append({ test: 'test' });
-}}
-
-// ✅ The following is correct and second action is triggered after next render
-handleChange={() => {
- append({ test: 'test' });
-}}
-React.useEffect(() => {
- if (fields.length === 2) {
- remove(0);
- }
-}, fields)
- `}
- />
-
- 만약 useFieldArray 를 사용하는 경우, 배열 인풋을
- 등록할 때 {`ref={register}`} 대신{" "}
- {`ref={register()}`} 형태로 사용하는 것이 중요합니다.
- 그래야 register 가 배열의 map 함수
- 안에서 수행됩니다.
+ 입력값을 다시 검사하는 것은 사용자의 행동에 따라 한 필드당
+ 하나씩만 동작합니다. 왜냐하면 라이브러리 자체에서 에러 객체의 특정
+ 필드를 대조해보고 그에 따라 리랜더링을 실행하기 때문입니다.
-
- useEffect의 사용자 정의 레지스터에서는 작동하지
- 않습니다.
-
>
),
- table: (
- <>
-
-
- fields
-
-
-
- object & {`{ id: string }`}
-
-
-
- 이 객체는 input 을 생성하고 랜더링하기 위한 주요 객체(source of
- truth)입니다.
-
- 중요: 모든 입력 필드는
- 비제어 상태이기 떄문에, map 으로 생성되는 컴포넌트에
- id 값을 필수로 전달해주어야 합니다. 그래야 리액트가
- 어떤 아이템이 추가되고, 변경되고, 제거되는지 파악할 수 있습니다.
-
-
- 예: {`{fields.map(d => )}`}
-
-
-
-
-
- append
-
-
-
- (obj: object | object[]) => void
-
-
-
입력 필드(들)를 현재 필드들 마지막에 추가합니다.
-
-
-
- prepend
-
-
-
- (obj: object | object[]) => void
-
-
-
입력 필드(들)를 현재 필드들 맨 앞에 추가합니다.
-
-
-
- insert
-
-
-
- (index: number, value: object) => void
-
-
-
입력 필드(들)를 특정 위치에 추가합니다.
-
-
-
- swap
-
-
-
- (from: number, to: number) => void
-
-
-
입력 필드(들)의 위치를 서로 교체합니다.
-
-
-
- move
-
-
-
- (from: number, to: number) => void
-
-
-
- 입력 필드(들)를 다른 위치로 이동합니다.
-
- 참고:move{" "}
- 와 swap 의 차이점을 설명하자면, move 를
- 계속 호출하는 것은 입력 필드(들)를 임의의 공간 안에 집어넣는 것과
- 비슷하고, swap 은 두 입력 필드들의 위치만 바꾸는
- 것입니다.
-
-
-
-
-
- remove
-
-
-
- (index?: number | number[]) => void
-
-
-
- 특정 위치에 있는 입력 필드(들)를 제거합니다. 인덱스를 넣지 않았다면
- 전체를 제거합니다.
-
- 이 함수는
-
- Joi
-
- ,{" "}
-
- Superstruct
- {" "}
- 등의 외부 유효성 검사 방법들을 실행할 수 있도록 합니다. 실제로, 이
- 함수의 목적은 단순히 외부 유효성 검사 라이브러리로 Yup 등을 제한된
- 범위로 지원하는 정도에서 끝나지 않습니다. 우리는 다양한 라이브러리가
- React Hook Form 과 함께 동작할 수 있도록 지원하려 합니다. 심지어
- 유효성 검사를 위해 직접 커스터마이징할 수도 있습니다.
-
-
- 참고: 반드시{" "}
- values 와 errors 객체를 모두 포함하여
- 리턴시키세요, 그리고 이 객체들의 기본값은 빈 객체 {`{}`}{" "}
- 가 되어야 합니다.
-
-
- 참고: errors 객체의 키 값은
- 반드시 인풋 값과 연결되어야 합니다.
-
-
- 참고: 이 함수는
- validationSchema와 유사한 사용자 정의 후크 내부에
- 캐시되며, validationContext는 다시 렌더링 할 때마다
- 변경할 수있는 변경 가능한 객체입니다.
-
-
- 참고: 입력값을 다시 검사하는
- 것은 사용자의 행동에 따라 한 필드당 하나씩만 동작합니다. 왜냐하면
- 라이브러리 자체에서 에러 객체의 특정 필드를 대조해보고 그에 따라
- 리랜더링을 실행하기 때문입니다.
-
- >
+
+ watch API 와 같은 기능을 공유하고 있지만, 이 훅은 컴포넌트
+ 레벨의 리랜더링을 격리할 수 있으며 여러분의 애플리케이션에 더 나은
+ 퍼포먼스를 제공할 수 있습니다.
+
),
},
}
diff --git a/src/data/kr/devtools.tsx b/src/data/kr/devtools.tsx
index 55f70afcc..5865415bd 100644
--- a/src/data/kr/devtools.tsx
+++ b/src/data/kr/devtools.tsx
@@ -9,8 +9,8 @@ export default {
step1: (
<>
1단계: {" "}
- react-hook-form-devtools 를 개발 의존성(dev dependency)
- 패키지로 설치하세요.
+ @hookform/devtools 를 개발 의존성(dev dependency) 패키지로
+ 설치하세요.
>
),
step2: (
diff --git a/src/data/kr/faq.tsx b/src/data/kr/faq.tsx
index 238f6dca2..3de9436c7 100644
--- a/src/data/kr/faq.tsx
+++ b/src/data/kr/faq.tsx
@@ -1,11 +1,12 @@
import * as React from "react"
import colors from "../../styles/colors"
-import typographyStyles from "../../styles/typography.module.css"
-import buttonStyles from "../../styles/button.module.css"
-import tableStyles from "../../styles/table.module.css"
-import CodeArea from "../../components/CodeArea"
+import enzymeInput from "../../components/codeExamples/enzymeInput"
import focusController from "../../components/codeExamples/focusController"
import toggleFields from "../../components/codeExamples/toggleFields"
+import CodeArea from "../../components/CodeArea"
+import typographyStyles from "../../styles/typography.module.css"
+import tableStyles from "../../styles/table.module.css"
+import buttonStyles from "../../styles/button.module.css"
export default {
title: "자주 묻는 질문",
@@ -129,7 +130,7 @@ export default {
사실 ref 없이 register 를 할 수 있습니다.
수동으로 setValue, setError 그리고{" "}
- triggerValidation 를 사용하면 됩니다.
+ trigger 를 사용하면 됩니다.
@@ -198,20 +199,20 @@ export default {
먼저, 모든 라이브러리들은 폼을 만드는 과정을 쉽고 좋게 만들겠다는
공통의 문제를 해결하려고 합니다. 하지만 세 라이브러리는 약간
- 근본적인 차이를 가지고 있고, react-hook-form 은 비제어 입력을
- 기본으로 삼고 있습니다. 그리하여 여러분의 폼이 최대한의 퍼포먼스를
- 내고 최소한의 리랜더링만 발생하도록 합니다. 그 위에 react-hook-form
- 은 리액트 훅을 기반으로 만들어졌으며 훅으로 사용됩니다. 따라서
- 별도의 컴포넌트를 불러올 필요가 없습니다. 아래에 더 자세한 차이점을
- 표기했습니다.
+ 근본적인 차이를 가지고 있고, react-hook-form 는 기본적으로 비제어
+ 컴포넌트를 활용하고 있습니다. 그리하여 여러분의 폼이 최대한의
+ 퍼포먼스를 내고 최소한의 리랜더링만 발생하도록 합니다. 그 위에
+ react-hook-form 은 리액트 훅을 기반으로 만들어졌으며 훅으로
+ 사용됩니다. 따라서 별도의 컴포넌트를 불러올 필요가 없습니다. 아래에
+ 더 자세한 차이점을 표기했습니다.
React-hook-form 은 사용자가 제어되는 폼을 만들도록 권장하진 않지만{" "}
@@ -379,14 +401,29 @@ export default {
description: (
+
+
+ 왜 리액트 네이티브 환경(
+ react-native-testing-library)에서 테스트가 되지
+ 않나요?
+
+
+
+ React Hook Form 은 서버 사이드 랜더링 중에는 인풋을 등록할 수
+ 없습니다. 따라서 리액트 네이티브 환경에서 테스트 할 때{" "}
+ window 객체가 undefined 가 됩니다.
+ 간단히 고치는 방법으로 window 객체를 스텁(stub)으로
+ 만들면 등록이 가능합니다.
+
+
왜 act 경고가 뜨나요?
- React Hook Form 의 모든 유효선 검사 방법은 비동기 함수로
- 다루어집니다. 따라서{" "}
+ React Hook Form 의 모든 유효성 검사 메서드는 async 함수로
+ 처리됩니다. 따라서{" "}
act
{" "}
- 부분을 async 로 감싸주는게 중요합니다.
+ 함수 실행 시 async 를 감싸주는 것이 중요합니다.
-
왜 입력값이 바뀔 때 이벤트가 발생하나요?
+
왜 입력값을 바꿀 때 이벤트가 발생하지 않나요?
- React Hook Form 은 입력값이 변화할 때 input{" "}
- 이벤트를 사용합니다. 따라서 react-testing-library{" "}
- 의 fireEvent.input 을 사용하면 쉽게 문제를 해결할
- 수 있습니다.
+ React Hook Form 은 입력값이 바뀔 때 input 이벤트를
+ 사용합니다. 만약 react-testing-library 를
+ 사용하고 계시다면, 손쉽게
+ fireEvent.input 로 바꾸면 됩니다. 여기{" "}
+
+ 예제 링크가 있습니다
+
+ .
+
+
+ 만약 enzyme 를 사용하고 계시다면, 인풋의 DOM
+ 노드에 수동으로 value 를 설정해주시고, input
+ 이벤트를 실행하셔야 합니다.
+
@@ -435,7 +487,7 @@ export default {
getValues: 커스텀 훅
- 안에 레퍼런스로 저장되어있는 값을 가져옵니다. 빠르고 리소스를
+ 안에 저장되어있는 값을 레퍼런스로 가져옵니다. 빠르고 리소스를
적게 먹습니다. 이 메서드는 리랜더링을 일으키지 않습니다.
- If you find difficult to make the autofocus with external controlled
- component. It is possible to disable the "autofocus on error"
- feature. Maybe this behavior will bring a better user experience in
- some cases. {`useForm({submitFocusError: false});`}
+ 제어되는 외부 컴포넌트에 자동으로 포커스를 맞추는 기능을 구현하는
+ 것이 어렵다면, "에러 발생 시 자동으로 포커스 옮기기" 기능을 비활성화
+ 할 수도 있습니다. 아마도 이렇게 만드는 것이 어떤 경우에는 더 나은
+ 사용자 경험을 제공해 줄 수도 있습니다. 사용 예:{" "}
+ {`useForm({shouldFocusError: false});`}
+
+ >
+ ),
+ },
+ {
+ title: "모달이나 탭 폼을 다룰 때는 어떻게 하나요?",
+ description: (
+ <>
+
+ React Hook Form 은 각각의 input 안의 상태를 담아두는 방식으로
+ 네이티브 폼의 동작을 활용하는 기본 원리를 가지고 있습니다. 이 원리를
+ 이해하는 것이 중요합니다(커스텀 register 를{" "}
+ useEffect 안에서 실행하는 경우 제외). 모달이나 탭의
+ 폼을 다룰 때 흔히 잘못 이해하는 부분 중 하나가 폼/인풋 을 마운트하고
+ 언마운트할 때 입력 상태가 그대로 남아있으리라 생각하는 것입니다.
+ 대신 올바르게 구현하려면 모달이나 각각의 탭 안에 폼을 새로이
+ 만들면서 각각의 단계별 데이터를 지역 상태나 전역 상태로 보존하셔야
+ 합니다.
+ React Hook Form 은{" "}
+
+ Yup
+
+ ,{" "}
+
+ Superstruct
+ {" "}
+ &{" "}
+
+ Joi
+
+ 을 활용하여 스키마 기반의 폼 유효성 검사를 제공합니다.{" "}
+ validationSchema 를 useForm 에
+ 넘겨주어 추가 설정을 할 수 있습니다. React Hook Form 은 입력된
+ 데이터를 스키마와 비교하여 에러 혹은 알맞은
+ 결과를 표시합니다.
+
+ >
+ ),
+ step1: (
+ <>
+
+ 1단계:Yup 을
+ 프로젝트에 설치합니다.
+
+ >
+ ),
+ step2: (
+
+ 2단계: 유효성 검사를 위한
+ 스키마를 작성하고 React Hook Form 을 사용하여 인풋을 등록합니다.
+
+ ),
+ },
}
diff --git a/src/data/kr/migrateV5ToV6.tsx b/src/data/kr/migrateV5ToV6.tsx
new file mode 100644
index 000000000..5c11c9e6d
--- /dev/null
+++ b/src/data/kr/migrateV5ToV6.tsx
@@ -0,0 +1,275 @@
+import CodeArea from "../../components/CodeArea"
+import validationSchema from "../../components/codeExamples/validationSchema"
+import * as React from "react"
+import typographyStyles from "../../styles/typography.module.css"
+
+export default (
+ <>
+
안녕,
+
+ 다음은 조정해야 할 주요 변경 사항입니다. 우리는 진심으로 희망합니다 이러한
+ 변경 사항이 코드베이스에 너무 많은 문제를 일으키지 않습니다. 만약 너라면
+ 배후에있는 이성적인 것들이 궁금합니다. {""}
+
+ pull request
+ {" "}
+ 자세한 사항은.
+
+
+
+ ❤️ React hook Form Team
+
+
+
+
+
+
+
+
useForm:
+
+
+
+ 모든 구성에 대해 validation 접두사를 제거하고 있습니다.
+
+
+
+
+
+
+
validationSchema:
+
+
+ validationSchema가 표준으로 대체되었습니다 {""}
+ resolver로 Yup, Joi 및 Superstruct를 순간. 더 많은 스키마를
+ 지원하는 공식 리졸버 라이브러리가 있습니다 미래에 검증.
+
+
+
+ npm install @hookform/resolvers
+
+
+
+
+
+
Controller:
+
+
+ 우리는 Controller의 API를 훨씬 간단하게 만들었습니다.
+ 소품이 제거되었고 렌더러 소품으로 대체되었습니다.
+
+ 이 타입은 useFormContext 훅을 사용하는 대신 직접{" "}
+ Context 와 Consumer 를 사용할 때 유용합니다.
+
+ ),
+ },
+}
diff --git a/src/data/languages.js b/src/data/languages.js
index 5d228e6c1..cfc041ec4 100644
--- a/src/data/languages.js
+++ b/src/data/languages.js
@@ -1,4 +1,4 @@
module.exports = {
- langs: ['en', 'es', 'jp', 'zh', 'kr', 'pt', 'ru'],
- defaultLangKey: 'en'
-};
+ langs: ["en", "es", "jp", "zh", "kr", "pt", "ru"],
+ defaultLangKey: "en",
+}
diff --git a/src/data/nav.tsx b/src/data/nav.tsx
index fdabeefae..fd50184bc 100644
--- a/src/data/nav.tsx
+++ b/src/data/nav.tsx
@@ -67,7 +67,7 @@ export default {
builder: "폼 빌더",
faqs: "FAQs",
releases: "릴리즈",
- resources: "자원",
+ resources: "외부 리소스",
},
jp: {
home: "ホーム",
diff --git a/src/data/pt/advanced.tsx b/src/data/pt/advanced.tsx
index eebb9efaa..759da7c57 100644
--- a/src/data/pt/advanced.tsx
+++ b/src/data/pt/advanced.tsx
@@ -4,6 +4,7 @@ import { Link as PageLink } from "gatsby"
import accessibleCodeBase from "../../components/codeExamples/accessibleCodeBase"
import accessibleCodeFinal from "../../components/codeExamples/accessibleCodeFinal"
import { step1, step2, step3 } from "../../components/codeExamples/formWizard"
+import * as CodeExampleTestingForm from "../../components/codeExamples/testingForm"
import smartForm from "../../components/codeExamples/smartForm"
import form from "../../components/codeExamples/form"
import input from "../../components/codeExamples/input"
@@ -302,43 +303,11 @@ export default {
>
link para esta implementação.
{" "}
- com Controller.
+ com Controller.
>
),
},
- schema: {
- title: "Validação de formulário",
- description: (
- <>
-
- React Hook Form suporta esquema baseado na validação do formulário com{" "}
-
- Yup
-
- , aqui você utiliza o validationSchema para{" "}
- useForm como configuração opcional. React
- Hook Form irá validar o campo com base no esquema e retornará com{" "}
- errors ou um valor válido.
-
- >
- ),
- step1: (
- <>
-
- Passo 1: Instale o{" "}
- Yup em seu projeto.
-
- >
- ),
- step2: (
-
- Passo 2: Crie um esquema para
- validação e registre (register) os campos com React Hook
- Form.
-
+ Os testes são muito importantes porque preservam o código de bugs ou
+ erros e garantir a segurança do código quando você refatorar a base de
+ código.
+
+
+
+ Recomendamos o uso do{" "}
+
+ testing-library
+
+ , porque é simples e os testes são mais focados no comportamento do
+ usuário.
+
+
+
♦
+
+
+ Step 1: Prepare seus testes
+ ambiente.
+
+
+
+ Favor instalar mutationobserver-shim porque uso de forma
+ de reação MutationObserver para detectar entradas obter
+ não montado desde o DOM.
+
+
+
+
+
+ Criar setup.js para importar{" "}
+ mutationobserver-shim.
+
+
+
+
+ Finalmente, você tem que atualizar setup.js in{" "}
+ jest.config.js para incluir o arquivo.
+
+
+
+
+
+ Step 2: Criar formulário de
+ login.
+
+
+
+ Estabelecemos o atributo do papel de acordo. Estes atributos são útil
+ quando você vai escrever testes e melhorar a acessibilidade. Para mais
+ informações, você pode se referir ao{" "}
+
+ testing-library
+ {" "}
+ documentação. Traduzido com a versão gratuita do tradutor -
+ www.DeepL.com/Translator
+
+
+
+
+
+ Step 3: Escrever testes.
+
+
+
Os critérios a seguir são o que tentamos cobrir com os testes:
+
+
+
+
Falha na submissão de testes.
+
+
+ Estamos usando o método waitFor e find*{" "}
+ para detectar feedback de apresentação porque{" "}
+ handleSubmit é executado de forma assíncrona.
+
+
+
+
Validação de teste associada a cada entrada.
+
+
+ Estamos usando o método *ByRole ao consultar
+ diferentes elementos porque é assim que os usuários reconhecem seu
+ componente UI.
+
+
+
+
Testar a submissão com sucesso.
+
+
+
+
+ >
+ ),
+ },
}
diff --git a/src/data/pt/api.tsx b/src/data/pt/api.tsx
index 3c54b7a61..80b2c3351 100644
--- a/src/data/pt/api.tsx
+++ b/src/data/pt/api.tsx
@@ -1,12 +1,11 @@
import * as React from "react"
import colors from "../../styles/colors"
-import Popup from "../../components/Popup"
-import generic from "../generic"
import CodeArea from "../../components/CodeArea"
import useFieldArrayArgument from "../../components/codeExamples/useFieldArrayArgument"
+import generic from "../generic"
import typographyStyles from "../../styles/typography.module.css"
import buttonStyles from "../../styles/button.module.css"
-import code from "../../components/codeExamples/defaultExample"
+import tableStyles from "../../styles/table.module.css"
export default {
title: "API Documentação",
@@ -16,11 +15,6 @@ export default {
},
useForm: {
title: "useForm",
- intro: (
- <>
- Utilizando useForm, você receberá os seguintes métodos{" "}
- >
- ),
description: (
useForm também tem argumentos opcionais. O exemplo a
@@ -49,7 +43,7 @@ export default {
<>
Esse objeto de contexto será injetado no segundo argumento de{" "}
- validationResolver ou em{" "}
+ resolver ou em{" "}
),
+ validationOnAll: (
+ <>
+ A validação será acionada nos eventos blur e{" "}
+ change. Aviso: assim como no modo onChange,{" "}
+ all pode ter um impacto significativo no desempenho.
+ >
+ ),
defaultValues: (goToSection) => (
<>
@@ -159,7 +160,7 @@ export default {
Esta opção permite configurar quando entradas com erros são exibidas e
revalidadas (por padrão, a validação é acionada durante uma entrada
- mudança.)
+ mudança.)
- Setar esta opção para true irá habilitar a validação nativa
- do navegador. Você pode{" "}
-
- veja mais sobre as validações imbutidas no navegador
-
- , e veja também a seção{" "}
- goToSection("nativeValidation")}
- >
- nativeValidation
- {" "}
- para mais detalhes e exemplos.
+ Por padrão, quando as entradas são removidas, o React Hook Form usa{" "}
+ MutationObserver para detectar e{" "}
+ cancelar o registro daquelas entradas que são desmontadas.
+ No entanto, você pode definir shouldUnregister como{" "}
+ false para impedir a perda do estado de entrada devido à
+ desmontagem.
),
},
@@ -392,34 +382,6 @@ export default {
Objeto contendo erros de formulário, ou mensagens de erro que
pertencem a cada campo.
-
-
- {generic.note[currentLanguage]}:
- {" "}
- Diferença entre a versão 3 e 4:
-
-
-
-
-
Versão 4: Objetos aninhados
-
- Razão: com o encadeamento opcional se tornando
- mais popular entre a comunidade e para dar melhor suporte a tipo.
-
-
- {`errors?.yourDetail?.firstName;`}
-
-
-
-
Versão 3: Objetos nivelados
-
- Razão: simples e fácil de acessar o erro.
-
-
- {`errors['yourDetail.firstName'];`}
-
-
-
>
),
types: (
@@ -427,11 +389,23 @@ export default {
Isto é útil para validação de campos como regras de senha, com múltiplos
errors que precisam ser retornados de um único campo. Para habilitar
essa funcionalidade, tenha certeza de setar{" "}
- validateCriteriaMode: 'all'.
+ criteriaMode 'all'.
>
),
message: `'Message' é um campo string e vazio por padrão. Entretanto, se você registrar a validação com mensagem de erro, ele será retornado.`,
ref: `Referência para o elemento do campo.`,
+ note: (goToSection) => (
+
+ Nota: você pode usar o{" "}
+ goToSection("ErrorMessage")}
+ >
+ ErrorMessage
+ {" "}
+ para ajudar a lidar com seus estados de erro.
+
+ ),
},
watch: {
title: "watch",
@@ -478,7 +452,6 @@ export default {
),
multiple: "Assista múltiplos campos",
all: "Assista todos os campos",
- nest: "Assista a todas as entradas e retorne objeto aninhado",
},
},
handleSubmit: {
@@ -500,7 +473,7 @@ export default {
Essa função irá limpar o valor dos campos, e erros dentro do
- formulário. Ao fornecer omitResetState , você tem a
+ formulário. Ao fornecer omitResetState, você tem a
liberdade de redefina apenas parte específica do estado. Você pode
passar values como valor opcional para resetar o
formulário assinado com o valor padrão.
@@ -539,9 +512,9 @@ export default {
Nota: Você vai precisar
- fornecer defaultValues durante useForm
- ou reset com valor para redefinir no
- Controller o valor dos componentes.
+ fornecer defaultValues durante useForm
+ oureset com valor para redefinir no
+ Controllero valor dos componentes.
>
),
@@ -552,17 +525,33 @@ export default {
<>
A função permite você manualmente setar um ou múltiplos erros.
-
- Nota: este método não
- persistirá o erro e bloqueará a ação de envio. É mais útil durante a
- função handleSubmit quando você deseja fornecer feedback
- de erro aos usuários após a validação assíncrona.
-
+
+
+
+ Este método não persistirá o erro de entrada associado se a
+ entrada passe na validação.
+
+
+
+
+ Defina um erro que não esteja associado a um campo de entrada.
+ persistir e necessário para remoção manual com{" "}
+ clearError.
+
+
+
+
+ É útil durante a função handleSubmit quando você
+ deseja fornecer feedback de erro aos usuários após a validação
+ assíncrona.
+
- Essa função vai retornar todo o dado do formulário, e é útil em uma
- função quando você precisa capturar os dados do formulário.
+ Esta função irá ajudá-lo a ler os valores do formulário. A diferença
+ entre watch é getValues não será acionado
+ renderize novamente ou inscrito nas alterações de entrada. As funções
+ abrangem:
- Por padrão getValues() irá retornar todo o dado do
- formulário em uma estrutura plana. ex:{" "}
- {`{ test: 'data', test1: 'data1'}`}
+ getValues(): lê valores inteiros do formulário.
+
+
+
+
+ getValues('test'): lê o valor de entrada individual
+ por
+ name.
- Trabalhando com campos definidos do formulário,{" "}
- getValues({`{ nest: true }`}) irá retornar o dado em
- uma estrutura aninhada de acordo com o campo name.
- ex: {`{ test: [1, 2], test1: { data: '23' } }`}
+ getValues(['test', 'test1']): lê várias entradas por
+ names.
- Se você preferir, pode centralizar a validação de regras com validação
- externa, validação de esquema, você pode aplicar{" "}
- validationSchema em useForm como argumento
- opcional. React Hook Form atualmente suporta{" "}
-
- Yup
- {" "}
- para validação de esquema de objeto.
-
- Componente controlado. ex: as="input" ou{" "}
- {`as={}`}
+ O controlador injeta onChange, onBlur {""}
+ e value adota o componente.
+ }
+ control={control}
+ name="test"
+/>
+`}
+ />
- control
+ render
- Object
+ Function
-
✓
+
- control objeto é invocado do useForm. é
- opcional, se estiver usando o FormContext.
+ Este é um{" "}
+
+ render prop
+
+ . Uma função que retorna um elemento React e fornece a capacidade de
+ anexar eventos e valor ao componente. Isso facilita integrar com
+ componente controlado externo com acessórios não-padrão nome:{" "}
+ onChange, onBlur e value.
+ (
+
+ ))
+/>
+ } />`}
+ />
@@ -750,9 +780,9 @@ export default {
Note: se o seu formulário
- invocar reset com valores diferentes, você
- precisará fornecer defaultValues no nível useForm em
- vez de definido inline defaultValue..
+ invocar reset com valores diferentes, você precisará
+ fornecer defaultValues no nível useForm em vez de
+ definido inline defaultValue..
@@ -766,48 +796,34 @@ export default {
Regras de validação de acordo com o register.
-
-
-
-
- onChange
-
-
-
- (args: any | EventTarget) => any
-
-
-
-
- A propriedade onChange lhe permite customizar o retorno
- do valor, verifique se o formato do componente externo{" "}
- value props.
+
+
+ Estado local: entrada register com validação
+ atualizada regras ou unregister de entrada em{" "}
+ useEffect e deixe o Controller se
+ registrar novamente com rules atualizadas.
+
+
+ Estado de entrada: utilize a função validate com{" "}
+ getValues para retornar sua validação
+ condicionalmente.
+
+
event.target.value}}
-onChange={{([ event, data ]) => ({ checked: data.checked})}}`}
+ rawData="
+register('name', { required: state })
+validate: (value) => value === getValues('firstName');"
/>
-
-
- onChangeName
-
-
- string
-
-
-
- Este propridade lhe permite marcar eventos específicos, ex: quando{" "}
- onChange evento é chamado onTextChange
-
- Esta propridade lhe permite marcar eventos específicos, ex: quando o{" "}
- onBlur evento é chamado onTextBlur
-
-
-
-
- valueName
-
-
- string
-
-
-
- Esta propriedade lhe permite sobrescrever a propriedade{" "}
- value e suporta outros componentes que não utilizam a
- propriedade value. ex: checked,{" "}
- selected e outros...
-
- O exemplo a seguir demonstra como você pode aproveitar a validação do
- navegador. Você apenas precisa setar nativeValidation{" "}
- para true e o restante da sintaxe é igual à validação
- padrão.
-
-
- Note: This feature has been
- removed in V4 due to low usage, but you can still use it in V3
-
- >
- ),
+ table: {
+ name: <>campo name associado.>,
+ errors: (
+ <>
+ errors objeto do React Hook Form. é opcional se estiver
+ usando FormContext.
+ >
+ ),
+ message: <>mensagem de erro em linha.>,
+ as: (
+ <>
+ Um componente ou tag HTML. ex: as="span" or{" "}
+ {`as={}`}
+ >
+ ),
+ render: (
+ <>
+ Este é um{" "}
+
+ render prop
+ {" "}
+ para renderizar mensagem de erro ou mensagens.
+
+ Note: you need to set{" "}
+ validateCriteriaMode to 'all' for using messages.
+
+ >
+ ),
+ },
},
useFieldArray: {
title: "useFieldArray",
@@ -1059,7 +985,58 @@ onChange={{([ event, data ]) => ({ checked: data.checked})}}`}
{" "}
para comparar arrays controlados e não controlados.
-
Esse hook fornece os seguintes objetos e funções:
+
+
+
+
+
+
{generic.name.pt}
+
{generic.type.pt}
+
{generic.required.pt}
+
{generic.description.pt}
+
+
+
+
+
+ name
+
+
+ string
+
+
+
+ <>campo name associado.>
+
+
+
+
+ control
+
+
+ Object
+
+
+
{generic.control.pt}
+
+
+
+ keyName
+
+
+
+ string = 'id'
+
+
+
+
+ valor da key da matriz de campos, o padrão é
+ "id", você pode mude o nome da chave.
+
- Nota: Tenha certeza que você
- retornando o objeto que contem values e{" "}
- errors, e seus valores padrão sejam um objeto vazio{" "}
- {`{}`}.
-
-
- Nota: retornar a chave do
- objeto que contenha os erros é relevante para seus inputs.
-
-
- Nota: Essa função será
- cacheada dentro do custom hook, similar ao{" "}
- validationSchema, enquanto o{" "}
- validationContext é um objeto mutável que pode ser
- modificado a cada re-render.
-
-
- Nota: Revalidar o input vai
- ocorrer somente em um campo por vez durante as interações do usuário,
- porque a biblioteca em si vai considerar o objeto do campo em
- especifico e disparará o re-render de acordo.
+ Apoiamos Yup, Joi e Superstruct oficialmente como{" "}
+
+ resolvedores padrão
+
+ .
+
+
+ npm install @hookform/resolvers
+
+
+
notas sobre a criação de resolvedores personalizados:
+
+
+
+
+ Nota: Tenha certeza que
+ você retornando o objeto que contem values e{" "}
+ errors, e seus valores padrão sejam um objeto vazio{" "}
+ {`{}`}.
+
+
+
+
+ Nota: retornar a chave do
+ objeto que contenha os erros é relevante para seus inputs.
+
+
+
+
+ Nota: Essa função será
+ cacheada dentro do custom hook, enquanto o context é
+ um objeto mutável que pode ser modificado a cada re-render.
+
+
+
+
+ Nota: Revalidar o input
+ vai ocorrer somente em um campo por vez durante as interações do
+ usuário, porque a biblioteca em si vai considerar o objeto do
+ campo em especifico e disparará o re-render de acordo.
+
+ Compartilhe a mesma funcionalidade que a API watch, no
+ entanto, isso isolará a nova renderização no nível do componente e
+ resultará potencialmente em melhor desempenho para sua aplicação.
+
Você pode atualmente usar o register em um campo sem o{" "}
ref. De fato, você pode manualmente usar{" "}
- setValue, setError e{" "}
- triggerValidation.
+ setValue, setError e trigger.
@@ -492,7 +491,7 @@ export default {
),
},
{
- title: "Controller not working with submitFocusError?",
+ title: "Controller not working with shouldFocusError?",
description: (
<>
@@ -505,7 +504,7 @@ export default {
- However, for some 3rd party controlled Components like{" "}
+ However, for some 3rd party controlled Components (like{" "}
{``} from MUI or {``}{" "}
from AntD) it's very difficult to predict his ref because the
formats changes, so React Hook Form will properly detect the
@@ -524,10 +523,50 @@ export default {
If you find difficult to make the autofocus with external controlled
component. It is possible to disable the "autofocus on error"
feature. Maybe this behavior will bring a better user experience in
- some cases. {`useForm({submitFocusError: false});`}
+ some cases. {`useForm({shouldFocusError: false});`}
>
),
},
+ {
+ title: "How to work with modal or tab forms?",
+ description: (
+ <>
+
+ É importante entender que o React Hook Form adota a forma nativa
+ comportamento pelo estado de entrada da loja dentro de cada entrada
+ (exceto
+ registre-se em useEffect). Um dos comuns
+ equívocos é quando se trabalha com formulários modais ou de guias,
+ montando e desmontar formulário / entradas que o estado das entradas
+ permanecerá. Isso é implementação incorreta, em vez disso, a solução
+ correta deve sempre criando um novo formulário para o formulário
+ dentro do modal ou de cada guia e capture seus dados de envio no
+ estado local ou global.
+
+ >
+ ),
+ },
],
}
diff --git a/src/data/pt/getStarted.tsx b/src/data/pt/getStarted.tsx
index bafd4fb79..9f05195ef 100644
--- a/src/data/pt/getStarted.tsx
+++ b/src/data/pt/getStarted.tsx
@@ -3,7 +3,10 @@ import code from "../../components/codeExamples/defaultExample"
import { Link } from "@reach/router"
import translateLink from "../../components/logic/translateLink"
import CodeArea from "../../components/CodeArea"
-import { uiLibraryHookInput } from "../../components/codeExamples/getStarted"
+import {
+ uiLibraryHookInput,
+ uiLibraryHookInputTs,
+} from "../../components/codeExamples/getStarted"
import typographyStyles from "../../styles/typography.module.css"
export default {
@@ -179,7 +182,12 @@ export default {
processo para você.
-
+
Opção 3: Por último, podemos
setar um registro customizado usando{" "}
@@ -235,4 +243,56 @@ export default {
>
),
},
+ schema: {
+ title: "Validação de formulário",
+ description: (
+ <>
+
+ React Hook Form suporta esquema baseado na validação do formulário com{" "}
+
+ Yup
+
+ ,{" "}
+
+ Superstruct
+ {" "}
+ &{" "}
+
+ Joi
+
+ , aqui você utiliza o validationSchema para{" "}
+ useForm como configuração opcional. React
+ Hook Form irá validar o campo com base no esquema e retornará com{" "}
+ errors ou um valor válido.
+
+ >
+ ),
+ step1: (
+ <>
+
+ Passo 1: Instale o{" "}
+ Yup em seu projeto.
+
+ >
+ ),
+ step2: (
+
+ Passo 2: Crie um esquema para
+ validação e registre (register) os campos com React Hook
+ Form.
+
+ ),
+ },
}
diff --git a/src/data/pt/migrateV5ToV6.tsx b/src/data/pt/migrateV5ToV6.tsx
new file mode 100644
index 000000000..fc39382db
--- /dev/null
+++ b/src/data/pt/migrateV5ToV6.tsx
@@ -0,0 +1,276 @@
+import CodeArea from "../../components/CodeArea"
+import validationSchema from "../../components/codeExamples/validationSchema"
+import * as React from "react"
+import typographyStyles from "../../styles/typography.module.css"
+
+export default (
+ <>
+
Hi there,
+
+ Here are the breaking changes you would need to adjust. We sincerely hope
+ those changes aren't creating too much trouble for your codebase. If you
+ are wondering some of the rationals behind, you can take a look at this{" "}
+
+ pull request
+ {" "}
+ for more details.
+
+
+
+ ❤️ React hook Form Team
+
+
+
+
+
+
+
+
useForm:
+
+
+
+ We are removing validation prefix for all the config.
+
+
+
+
+
+
+
validationSchema:
+
+
+ validationSchema has been replace with standard{" "}
+ resolver, and you can use Yup, Joi and Superstruct at the
+ moment. We have an official resolver library to support more schema
+ validation in the future.
+
+
+
+ npm install @hookform/resolvers
+
+
+
+
+
+
Controller:
+
+
+ We made Controller's API much simpler, and the following
+ props have been removed and replaced with render props.
+
+ I feel like forms in react can get quite complicated. React hook form
+ makes it slightly easier. This is a tutorial on how and why to use
+ react hook form.
+
+ Let's get back into forms and look at your recommendation
+ `react-hook-form`!
+
+ ),
+ },
+ {
+ title: "The best way to create forms in React",
+ url: "https://www.youtube.com/watch?v=bU_eq8qyjic&t=38s",
+ authorUrl: "https://www.youtube.com/user/satansdeer1",
+ author: "Maksim Ivanov",
+ description: (
+ <>
+
How to create forms in React.
+
+ Right now the best way to create forms in React is to use React Form
+ Hook library.
+
+ >
+ ),
+ },
+ {
+ title: "Easy Way of Form Validation with React Hook Form",
+ url: "https://www.youtube.com/watch?v=oXY_sSfjlSw",
+ authorUrl: "https://www.youtube.com/channel/UCS3-MF_4ADqglU2OSly4vIw",
+ author: "For Those Who Code",
+ description: (
+
+ In this video we will cover basics on how to validate form fields in
+ React with React hook forms which is performant and really easy
+ library to use.
+
+ Are you tired of the slow, painful process of setting up forms in
+ React, building out form state, validation, errors, and more? Worry no
+ more! With React Hook Form, create forms in a matter of minutes! It'll
+ be the easiest, fastest way you've ever built a form in React! Replace
+ your old, boring
+
+ ),
+ },
+ {
+ title: "How to test react hook form using react testing library",
+ url: "https://www.youtube.com/watch?v=hP0h2P3BdEE",
+ authorUrl: "https://www.youtube.com/user/satansdeer1",
+ author: "Maksim Ivanov",
+ description: (
+
How to test react hook form using react testing library:
+ ),
+ },
+ {
+ title: "React Hook Form Tutorial - How to Create a Custom Input",
+ url: "https://www.youtube.com/watch?v=bQRIBpKN8-s",
+ authorUrl: "https://www.youtube.com/user/satansdeer1",
+ author: "Maksim Ivanov",
+ description: (
+
+ Let's learn how to create a custom input for react-hook-form. We will
+ use a simple login form as an example React application.
+
+ React-hook-form supports file uploads. In this video I'll show you how
+ to upload files using react-hook-form. And also we'll update the
+ firebase file upload example with react-hook-form
+
+ Using React Hook Form with Ionic Framework React Components - this is
+ based on the blog post
+
+ ),
+ },
+ {
+ title:
+ "React Hook Form Talk and Demo by its Author Bill Luo aka@bluebill1049",
+ url: "https://www.youtube.com/watch?v=fpwnCGgc9A8",
+ authorUrl: "https://www.youtube.com/channel/UCorlLn2oZfgOJ-FUcF2eZ1A",
+ author: "ReactEurope",
+ description: "",
+ },
+ {
+ title: "#04 Curso de React Hooks [ React Hook Form ]",
+ url:
+ "https://www.youtube.com/watch?list=PLPl81lqbj-4KswGEN6o4lF0cscQalpycD&v=wgutyeQTGDA",
+ authorUrl: "https://www.youtube.com/user/Bluuweb",
+ author: "Bluuweb !",
+ description: "",
+ },
+ {
+ title:
+ "Does this library make Redux Form obsolete? | React Hook Form Tutorial | React Tutorials",
+ url: "https://www.youtube.com/watch?v=lHclVxcborY",
+ authorUrl: "https://www.youtube.com/channel/UCTD_PLq3KAUwkIIs9fk3pAA",
+ author: "Better Coding Academy",
+ description: "",
+ },
+ {
+ title:
+ "React Hook Form File Upload Tutorial - Upload Files to NodeJS API",
+ url: "https://www.youtube.com/watch?v=PEGUFi9Sx-U",
+ authorUrl: "https://www.youtube.com/user/satansdeer1",
+ author: "Maksim Ivanov",
+ description:
+ "React Hook Form tutorial on how to upload files to an ExpressJS API.",
+ },
+ {
+ title: "How to Validate File Uploads With React Hook Form",
+ url: "https://www.youtube.com/watch?v=tYGTjxhzrqY",
+ authorUrl: "https://www.youtube.com/user/satansdeer1",
+ author: "Maksim Ivanov",
+ description:
+ "In this video I show how to validate the file field in React using Yup and React Hook Form.",
+ },
+ {
+ title: "Form validation with Next.js/React part 2",
+ url: "https://www.youtube.com/watch?v=-scXzb-F_3k",
+ authorUrl: "https://www.youtube.com/channel/UCBA_4Q-Gk4bJxRrtpfdvTzw",
+ author: "EinCode",
+ description: "",
+ },
+ ],
+}
diff --git a/src/data/ru/advanced.tsx b/src/data/ru/advanced.tsx
index 20e8250d8..11ac65d22 100644
--- a/src/data/ru/advanced.tsx
+++ b/src/data/ru/advanced.tsx
@@ -3,6 +3,7 @@ import CodeArea from "../../components/CodeArea"
import accessibleCodeBase from "../../components/codeExamples/accessibleCodeBase"
import accessibleCodeFinal from "../../components/codeExamples/accessibleCodeFinal"
import { step1, step2, step3 } from "../../components/codeExamples/formWizard"
+import * as CodeExampleTestingForm from "../../components/codeExamples/testingForm"
import smartForm from "../../components/codeExamples/smartForm"
import form from "../../components/codeExamples/form"
import input from "../../components/codeExamples/input"
@@ -291,42 +292,11 @@ export default {
>
по этой ссылке.
{" "}
- с Controller.
+ с Controller.
>
),
},
- schema: {
- title: "Валидация по схеме",
- description: (
- <>
-
- React Hook Form поддерживает валидацию формы по схеме с{" "}
-
- Yup
-
- , где вы можете передать validationSchema в{" "}
- useForm как опциональную настройку. React
- Hook Form будет валидировать ваши поля ввода по схеме и возвращать
- либо ошибки, либо валидный результат.
-
- >
- ),
- step1: (
- <>
-
- Шаг 1: Установите{" "}
- Yup в проект.
-
- >
- ),
- step2: (
-
- Шаг 2: Настройте схему данных
- для валидации и зарегистрируйте поля ввода в React Hook Form.
-
- Imagine um cenário em que você tenha uma tabela de dados. Esta tabela
- pode contém centenas ou milhares de linhas e cada linha terá entradas.
- Uma prática comum é renderizar apenas os itens que estão no viewport,
- no entanto, isso causará problemas quando os itens forem removidos do
- o DOM quando estão fora de vista e adicionados novamente. Isso causará
- itens para redefinir seus valores padrão quando eles entrarem
- novamente na janela de exibição.
+ Представьте себе сценарий, в котором у вас есть таблица данных. Эта
+ таблица может содержат сотни или тысячи строк, и каждая строка будет
+ иметь входные данные. Обычной практикой является визуализация только
+ тех элементов, которые находятся в область просмотра, однако это
+ вызовет проблемы при удалении элементов из DOM, когда они вне поля
+ зрения, и снова добавлены. Это приведет к пунктам сбросить их значения
+ по умолчанию при повторном входе в область просмотра.
- Para contornar isso, você pode registrar manualmente os campos e, em
- seguida, definir programaticamente o valor do campo.
+ Чтобы обойти это, вы можете вручную зарегистрировать поля, а затем
+ программно установить значение поля.
- Um exemplo é mostrado abaixo usando{" "}
+ Пример показан ниже с использованием{" "}
),
},
+ testingForm: {
+ title: "Testing Form",
+ description: (
+ <>
+
+ Тестирование очень важно, потому что оно сохраняет код от ошибок или
+ ошибки и гарантируют безопасность кода при рефакторинге кодовой базы.
+
+
+
+ Мы рекомендуем использовать{" "}
+
+ testing-library
+
+ , потому что она проста и тесты больше ориентированы на поведение
+ пользователей.
+
+
+
♦
+
+
+ Step 1: Настройте вашу
+ тестовую среду.
+
+
+
+ Пожалуйста, установите mutationobserver-shim, потому что
+ повторное использование крючкообразной формы{" "}
+ MutationObserver для обнаружения входов получает не
+ смонтированный из МДМ.
+
+
+
+
+
+ Создайте setup.js для импорта ".
+ mutationobserver-shim.
+
+
+
+
+ Наконец, вы должны обновить setup.js в ".
+ jest.config.js для включения файла.
+
+
+
+
+
+ Step 2: Создайте форму входа
+ в систему.
+
+
+
+ Мы установили атрибут роли соответственно. Этими атрибутами являются
+ Полезно, когда вы будете писать тесты и улучшать доступность.
+ Подробнее информация, вы можете сослаться на " ".
+
+ testing-library
+ {" "}
+ Документация. Переведено с помощью www.DeepL.com/Translator
+ (бесплатная версия)
+
+
+
+
+
+ Step 3: Пишите тесты.
+
+
+
Следующие критерии мы пытаемся покрыть испытаниями:
+
+
+
+
Сбой подачи теста.
+
+
+ Мы используем метод waitFor и find* для
+ того, чтобы обнаружить обратную связь, потому что{" "}
+ handleSubmit метод выполняется асинхронно.
+
+
+
+
Проверка тестов, связанных с каждым входом.
+
+
+ Мы используем метод *ByRole при запросе различный
+ элементы, потому что именно так пользователи узнают ваш компонент
+ пользовательского интерфейса.
+
+
+
+
Успешная подача теста.
+
+
+
+
+ >
+ ),
+ },
}
diff --git a/src/data/ru/api.tsx b/src/data/ru/api.tsx
index e58654bb3..0e21d317a 100644
--- a/src/data/ru/api.tsx
+++ b/src/data/ru/api.tsx
@@ -1,11 +1,11 @@
import * as React from "react"
import colors from "../../styles/colors"
-import Popup from "../../components/Popup"
import CodeArea from "../../components/CodeArea"
import useFieldArrayArgument from "../../components/codeExamples/useFieldArrayArgument"
+import generic from "../generic"
import typographyStyles from "../../styles/typography.module.css"
import buttonStyles from "../../styles/button.module.css"
-import code from "../../components/codeExamples/defaultExample"
+import tableStyles from "../../styles/table.module.css"
export default {
title: "Документация по API",
@@ -15,11 +15,6 @@ export default {
},
useForm: {
title: "useForm",
- intro: (
- <>
- Вызывая useForm, вы получите следующие методы{" "}
- >
- ),
description: (
useForm также имеет необязательные аргументы. В
@@ -29,25 +24,26 @@ export default {
validationResolver: (goToSection) => (
<>
- This callback function allow you to run through any schema or custom
- validation. The function has the entire form values as
- argument, and you will need to validate the result and return both{" "}
- values and errors. Read more at{" "}
+ Эта функция обратного вызова позволяет запускать любую схему или
+ пользовательские Проверка. Функция имеет всю форму{" "}
+ values как аргумент, и вам нужно будет проверить
+ результат и вернуть оба значения и ошибки.
+ Узнайте больше на кнопка
goToSection("validationResolver")}
>
validationResolver
{" "}
- section.
+ раздел.
>
),
validateContext: (
<>
- This context object will be injected into{" "}
- validationResolver's second argument or{" "}
+ Этот контекстный объект будет внедрен в resolver
+ Второй аргумент или{" "}
Yup
{" "}
- validation's context object.
+ объект контекста проверки.
>
),
@@ -90,6 +86,14 @@ export default {
считается, что это ухудшает производительность.
>
),
+ validationOnAll: (
+ <>
+ Валидация активируется в событиях blur и{" "}
+ change. Предупреждение: как и в режиме{" "}
+ onChange, all
+ может оказать существенное влияние на производительность.
+ >
+ ),
defaultValues: (goToSection) => (
<>
@@ -157,7 +161,7 @@ export default {
Этот параметр позволяет установить, когда поля с ошибками будут повторно
валидироваться (по умолчанию проверка запускается при любом изменении в
- поле).
+ поле).
- Устанавливая эту опцию в true включит нативную браузерную
- валидацию. Вы можете{" "}
-
- узнать больше о браузерной валидации
-
- , и перейти в раздел{" "}
- goToSection("nativeValidation")}
- >
- nativeValidation
- {" "}
- , где приведено больше деталей и примеров.
+ По умолчанию, когда входные данные удаляются, React Hook Form использует{" "}
+ MutationObserver для обнаружения и{" "}
+ отмены регистрации тех входных данных, которые отключаются.
+ Однако вы можете установить для shouldUnregister значение{" "}
+ false, чтобы предотвратить потерю состояния ввода из-за
+ размонтирования.
),
},
@@ -393,33 +386,6 @@ export default {
Объект, содержащий ошибки формы или сообщения об ошибках для каждого
поля.
-
-
- Примечание: Есть развница в
- V3 и V4:
-
-
-
-
-
V4: Вложеный объект
-
- Причина: так как опциональный чейнинг становится
- всё более популярным в сообществе и для поддержки лучшего типа.
-
-
- {`errors?.yourDetail?.firstName;`}
-
-
-
-
V3: Плоский объект
-
- Причина: простой доступ к ошибке.
-
-
- {`errors['yourDetail.firstName'];`}
-
-
-
>
),
types: (
@@ -427,11 +393,24 @@ export default {
Это полезно для проверки входных данных, таких как правила пароля,
которые должны возвращать несколько ошибок для одного поля. Чтобы
включить эту функцию, убедитесь, что вы установили{" "}
- validateCriteriaMode: 'all'.
+ criteriaMode 'all'.
>
),
message: `Сообщение является пустой строкой по умолчанию. Однако, если вы зарегистрируете валидацию с сообщением об ошибке, то затем она будет возвращена.`,
ref: `Ссылка на ваш элемент поля.`,
+ note: (goToSection) => (
+
+ Примечание: вы можете
+ использовать{" "}
+ goToSection("ErrorMessage")}
+ >
+ ErrorMessage
+ {" "}
+ чтобы помочь обработать ваши ошибки.
+
+ ),
},
watch: {
title: "watch",
@@ -477,7 +456,6 @@ export default {
),
multiple: "Наблюдение за несколькими полями",
all: "Наблюдение за всеми полями",
- nest: "Наблюдение за всеми полями и возврат вложенного объекта",
},
},
handleSubmit: {
@@ -500,7 +478,7 @@ export default {
Эта функция сбрасывает значения полей и ошибки формы. Поставив{" "}
- omitResetState , вы можете свободно только сбросить
+ omitResetState, вы можете свободно только сбросить
конкретный кусок состояния. Вы можете передать values в
качестве необязательного аргумента для сброса формы в присвоенные
значения по умолчанию.
@@ -539,9 +517,9 @@ export default {
Примечание: Вам нужно будет
- укажите defaultValues во время useForm
- или reset со значением для сброса
- Controller стоимость компонентов.
+ укажите defaultValues во время useForm
+ илиreset со значением для сброса
+ Controllerстоимость компонентов.
>
),
@@ -554,17 +532,27 @@ export default {
Эта функция даёт возможность вручную установать одну или несколько
ошибок.
-
- Примечание: этот метод не
- сохранит ошибку и заблокирует отправить действие. Это более полезно во
- время функции handleSubmit, когда Вы хотите отправить
- сообщение об ошибке пользователям после асинхронной проверки.
-
+
+
+
+ Этот метод не сохранит связанную ошибку ввода, если ввод пройти
+ проверку.
+
+
+ Установите ошибку, которая не связана с полем ввода будет сохранить
+ и требуется удалить вручную с помощью clearError.
+
+
+ Это полезно во время функции handleSubmit, когда вы
+ хотите дать сообщение об ошибке пользователям после асинхронной
+ проверки.
+
- Эта функция возвращает все данные формы, и это полезно, когда вы
- хотите получить значения полей формы.
+ Эта функция поможет вам прочитать значения формы. Разница между{" "}
+ watch это getValues не сработает повторно
+ сделать или подписаться на входные изменения. Функции охватывает:
- По умолчанию getValues() вернёт значения полей формы
- в виде плоской структуры, например:{" "}
- {`{ test: 'data', test1: 'data1'}`}
+ getValues ('test'): считывает индивидуальное
+ входное значение по
+ name.
+
+
+
+
+ getValues('test'): считывает индивидуальное входное
+ значение по
+ name.
- При работе с определёнными полями формы,{" "}
- getValues({`{ nest: true }`}) вернёт данные во
- вложенной структуре согласно имени поля, например:{" "}
- {`{ test: [1, 2], test1: { data: '23' } }`}
+ getValues(['test', 'test1']): считывание нескольких
+ входов
+ names.
- A custom hook for working with uncontrolled Field Arrays (dynamic
- inputs). The motivation behind this hook is to provide better user
- experience and form performance. You can watch{" "}
+ Пользовательский хук для работы с неуправляемыми массивами полей
+ (динамический входы). Мотивация этого крючка состоит в том, чтобы
+ обеспечить лучшего пользователя опыт и форма исполнения. Вы можете
+ посмотреть{" "}
this short video
{" "}
- to compare controlled vs uncontrolled Field Array.
+ {""}
+ сравнить контролируемый и неконтролируемый массив полей.
-
This hook provides the following object and functions.
+
+
+
+
+
{generic.name.ru}
+
{generic.type.ru}
+
{generic.required.ru}
+
{generic.description.ru}
+
+
+
+
+
+ name
+
+
+ string
+
+
+
+ <>имя связанного поля.>
+
+
+
+
+ control
+
+
+ Object
+
+
+
{generic.control.ru}
+
+
+
+ keyName
+
+
+
+ string = 'id'
+
+
+
+
+ массив ключ, значение по умолчанию «id», вы
+ можете измените имя ключа.
+
+
+
+
+
Important: {" "}
- useFieldArray is built on top of uncontrolled components.
- The following notes will help you aware and be mindful of its
- behaviour during implementation.
+ useFieldArray построен на основе неконтролируемых
+ компонентов. Следующие заметки помогут вам осознать и помнить его
+ поведение во время реализации.
- you can populate the fields by supply{" "}
- defaultValues at useForm hook.
+ Вы можете заполнить поля, указав {""}
+ defaultValues в ловушке useForm.
- make sure you assign id from fields{" "}
- object as your component key.
+ убедитесь, что вы присвоили id из fields{" "}
+ {""}
+ объект как ключ компонента.
- set defaultValue when you want to set default value
- or reset with inputs.
+ установите defaultValue, если вы хотите установить
+ значение по умолчанию или сброс с помощью входов.
- you can not call actions one after another. Actions need to be
- triggered per render.
+ Вы не можете называть действия одно за другим. Действия должны
+ быть срабатывает при рендере.
{
/>
- It's important to apply{" "}
- {`ref={register()}`} instead of{" "}
- {`ref={register}`} when working with{" "}
- useFieldArray so register will get invoked
- during map.
+ важно подать заявку {""}
+ {`ref = {register ()}`} вместо {""}
+ {`ref = {register}`} при работе с {""}
+ useFieldArray, поэтому будет вызван{" "}
+ register
+ во время map.
@@ -793,12 +850,15 @@ React.useEffect(() => {
- This object is the source of truth to map and render inputs.
+ Этот объект является источником правды для отображения и отображения
+ входных данных.
- Important: because each
- inputs can be uncontrolled, id is required with
- mapped components to help React identify which items have changed,
- are added, or are removed.
+ Important:
+ потому что каждый входы могут быть неуправляемыми,
+ id
+ {" "}
+ требуется с сопоставленные компоненты, чтобы помочь React
+ определить, какие элементы были изменены, добавлены или удалены.
- (from: number, to: number) => void
+ (from: number, to: number) => void
-
Swap input/inputs position.
+
Поменяйте местами вход / выход.
@@ -864,17 +925,17 @@ React.useEffect(() => {
- (from: number, to: number) => void
+ (from: number, to: number) => void
- Move input/inputs to another position.
+ Переместите вход / вход в другую позицию.
- Note: difference between{" "}
- move and swap, keep calling{" "}
- move will push input/inputs in a loop, while{" "}
- swap only change two input/inputs' position.
+ Примечание. разница
+ между move и swap, продолжайте звонить{" "}
+ move будет помещать ввод / ввод в цикл, тогда как{" "}
+ swap меняет только две позиции ввода / ввода.
@@ -885,13 +946,13 @@ React.useEffect(() => {
- (index?: number | number[]) => void
+ (index?: number | number[]) => void
- Remove input/inputs at particular position, or remove all when no
- index is provided.
+ Удалить вход / вход в определенной позиции или удалить все, когда
+ нет индекс предоставляется.
>
@@ -916,14 +977,66 @@ React.useEffect(() => {
as
+ Это
+
+ оказывать опору
+
+ , Функция, которая возвращает элемент React и предоставляет
+ возможность прикрепить события и значения в компонент. Это позволяет
+ легко интегрировать с внешним контролируемым компонентом с
+ нестандартными опорами name: onChange,{" "}
+ onBlur и value..
+ (
+
+ ))
+/>
+ } />`}
+ />
- control объект - это вызов формой useForm.
- Это необязательно, если вы используете FormContext.
-
+
{generic.control.ru}
@@ -957,10 +1067,10 @@ React.useEffect(() => {
defaultValues для useForm
- Note: if your form will
- invoke reset with different values, you will need to
- provide defaultValues at useForm level instead of set
- inline defaultValue.
+ Note: если ваша форма
+ будет вызовите reset с другими значениями, вам нужно
+ предоставить defaultValues на уровне useForm
+ вместо набора встроенный defaultValue.
@@ -974,52 +1084,33 @@ React.useEffect(() => {
Валидационные правила в соответствии с register.
-
-
-
-
- onChange
-
-
-
- (args: any | EventTarget) => any
-
-
-
-
- Параметр onChange позволяет вам изменять возвращаемое
- значение, убедитесь, что вы знаете форму реквизита{" "}
- value внешнего компонента. Атрибут value{" "}
- или checked будет считываться, когда форма полезных
- данных представляет собой object, который содержит
- атрибут type.
+
+
+ Локальное состояние: ввод register с обновленной
+ проверкой правила или unregister на{" "}
+ useEffect и позволить Controller{" "}
+ перерегистрировать себя с обновленными rules.
+
+
+ Состояние ввода: используйте функцию validate с{" "}
+ getValues для условного возврата проверки.
+
+
event.target.value}}
-onChange={{([ event, data ]) => ({ checked: data.checked})}}`}
+ rawData="
+register('name', { required: state })
+validate: (value) => value === getValues('firstName');"
/>
-
-
- onChangeName
-
-
- string
-
-
-
- Этот параметр позволяет вам настроить таргетинг на конкретное имя
- события, например: когда событие onChange называется{" "}
- onTextChange
-
- Этот параметр позволяет вам настроить таргетинг на конкретное имя
- события, например: когда событие onBlur называется{" "}
- onTextBlur
-
-
-
-
- valueName
-
-
- string
-
-
-
- Этот параметр позволяет переопределять свойство value и
- поддерживает другие компоненты, которые не используют свойство{" "}
- value, например: checked,{" "}
- selected и т.д.
-
-
),
description: (
@@ -1157,109 +1219,55 @@ onChange={{([ event, data ]) => ({ checked: data.checked})}}`}
Простой компонент для отображения связанного сообщения об ошибке поля.
),
- table: (
-
-
-
- name
-
-
- string
-
-
✓
-
имя связанного поля.
-
-
-
- errors
-
-
- object
-
-
-
- errors объект из React Hook Form. Необязательно, если
- вы используете FormContext.
-
-
-
-
- message
-
-
- string
-
-
-
встроенное сообщение об ошибке.
-
-
-
- as
-
-
-
- React.ElementType | string
-
-
-
-
- Компонент-обёртка или HTML тэг. Например: as="span" или{" "}
- {`as={}`}
-
- В следующем примере показано, как вы можете использовать браузерную
- валидацию. Вам нужно установить свойство nativeValidation{" "}
- в true, а остальная часть синтаксиса такая же, как для
- стандартной валидации.
-
-
- Note: This feature has been
- removed in V4 due to low usage, but you can still use it in V3
-
- >
- ),
+ table: {
+ name: <>имя связанного поля.>,
+ errors: (
+ <>
+ errors объект из React Hook Form. Необязательно, если вы
+ используете FormContext.
+ >
+ ),
+ message: <>встроенное сообщение об ошибке.>,
+ as: (
+ <>
+ Компонент-обёртка или HTML тэг. Например: as="span" или{" "}
+ {`as={}`}
+ >
+ ),
+ render: (
+ <>
+ Это{" "}
+
+ render prop
+ {" "}
+ сообщения об ошибке/ошибках.
+
+ Note: you need to set{" "}
+ validateCriteriaMode to 'all' for using messages.
+
- This function allow you to run any external validation methods, such
- as{" "}
+ Эта функция позволяет запускать любые внешние методы проверки, такие
+ как в виде{" "}
+
+ Yup
+
+ ,{" "}
({ checked: data.checked})}}`}
>
Superstruct
{" "}
- and etc. In fact, the goal is not only limited Yup as our external
- (schema) validation library. We would like to support many other
- validation libraries to work with React Hook Form. You can even write
- your custom validation logic to validate.
+ и т. д. На самом деле цель не ограничивается только Yup, как наши
+ внешние (схема) проверки библиотеки. Мы хотели бы поддержать многие
+ другие проверочные библиотеки для работы с React Hook Form. Вы даже
+ можете написать Ваша пользовательская логика проверки для
+ подтверждения.
- Note: make sure you are
- returning object which contains values and{" "}
- errors, and their default value should be empty object{" "}
- {`{}`}.
+ Мы официально поддерживаем Yup, Joi и Superstruct как
+
+ стандартные резольверы
+
+ .
-
- Note: returning errors
- object's key should be relevant to your inputs.
-
+
+ npm install @hookform/resolvers
+
-
- Note: this function will be
- cached inside the custom hook similar as validationSchema
- , while validationContext is a mutable object which can
- be changed on each re-render.
-
+
примечания по созданию пользовательских распознавателей:
-
- Note: re-validate input will
- only occur one field at time during user’s interaction, because the
- lib itself will evaluate the error object to the specific field and
- trigger re-render accordingly.
-
+
+
+
+ убедитесь, что вы возвращаете объект, который содержит {""}
+ values и error и их значения по
+ умолчанию значение должно быть {`{}`}.
+
+
+
+
+
+ возвращающий ошибки ключ объекта должен соответствовать вашим
+ входам.
+
+
+
+
+
+ эта функция будет кэшироваться внутри пользовательского хука, а{" "}
+ {""}
+ context - это изменяемый объект, который можно
+ изменить каждый рендер.
+
+
+
+
+
+ повторная проверка ввода будет происходить только одно поле за раз
+ в течение взаимодействие, потому что сама библиотека будет
+ оценивать объект ошибки в конкретное поле и триггер рендеринга
+ соответственно.
+
+ Используйте те же функции, что и API watch, однако это
+ будет изолировать повторный рендеринг на уровне вашего компонента и
+ потенциально приведет к лучшая производительность для вашего приложения.
+
+ ),
+ },
}
diff --git a/src/data/ru/devtools.tsx b/src/data/ru/devtools.tsx
index dc435f937..3bc08b17f 100644
--- a/src/data/ru/devtools.tsx
+++ b/src/data/ru/devtools.tsx
@@ -8,7 +8,7 @@ export default {
step1: (
<>
Step 1: install{" "}
- react-hook-form-devtools as a dev dependency package.
+ @hookform/devtools as a dev dependency package.
>
),
step2: (
diff --git a/src/data/ru/faq.tsx b/src/data/ru/faq.tsx
index f8c73a777..fe79fc86c 100644
--- a/src/data/ru/faq.tsx
+++ b/src/data/ru/faq.tsx
@@ -119,7 +119,7 @@ export default {
React Hook Form needs ref to collect the input value,
however, you may want to use ref for other purposes (eg.
- scroll into the view). The following example will show you how.
+ scroll into the view).
),
},
@@ -130,7 +130,7 @@ export default {
You can actually register an input without a{" "}
ref. In fact, you can manually setValue,{" "}
- setError and triggerValidation.
+ setError and trigger.
@@ -472,8 +472,8 @@ export default {
которые является причиной, почему React не распознает фактический
вклад, который имеет были обменены или отпущены. Как решение, вы
можете решить эту проблему проблема, предоставляя уникальный ввод{" "}
- key для вашего ввода. Вы также можете прочитать
- больше о ключевых реквизитах от {""}
+ key для вашего ввода. Вы также можете прочитать больше
+ о ключевых реквизитах от {""}
+ >
+ ),
+ },
],
}
diff --git a/src/data/ru/getStarted.tsx b/src/data/ru/getStarted.tsx
index 85acef8a6..885c28fc0 100644
--- a/src/data/ru/getStarted.tsx
+++ b/src/data/ru/getStarted.tsx
@@ -3,7 +3,10 @@ import code from "../../components/codeExamples/defaultExample"
import { Link } from "gatsby"
import translateLink from "../../components/logic/translateLink"
import CodeArea from "../../components/CodeArea"
-import { uiLibraryHookInput } from "../../components/codeExamples/getStarted"
+import {
+ uiLibraryHookInput,
+ uiLibraryHookInputTs,
+} from "../../components/codeExamples/getStarted"
import typographyStyles from "../../styles/typography.module.css"
export default {
@@ -198,7 +201,14 @@ export default {
компонента-обёртки Controller,
который сам позаботится о регистрации.
-
+
+
+
Вариант 3: И, наконец, мы
можем создать кастомную регистрацию с помощью{" "}
@@ -256,4 +266,35 @@ export default {
>
),
},
+ schema: {
+ title: "Валидация по схеме",
+ description: (
+ <>
+
+ React Hook Form поддерживает валидацию формы по схеме с{" "}
+
+ Yup
+
+ , где вы можете передать validationSchema в{" "}
+ useForm как опциональную настройку. React
+ Hook Form будет валидировать ваши поля ввода по схеме и возвращать
+ либо ошибки, либо валидный результат.
+
+ >
+ ),
+ step1: (
+ <>
+
+ Шаг 1: Установите{" "}
+ Yup в проект.
+
+ >
+ ),
+ step2: (
+
+ Шаг 2: Настройте схему данных
+ для валидации и зарегистрируйте поля ввода в React Hook Form.
+
+ ),
+ },
}
diff --git a/src/data/ru/migrateV5ToV6.tsx b/src/data/ru/migrateV5ToV6.tsx
new file mode 100644
index 000000000..b6b495e26
--- /dev/null
+++ b/src/data/ru/migrateV5ToV6.tsx
@@ -0,0 +1,277 @@
+import CodeArea from "../../components/CodeArea"
+import validationSchema from "../../components/codeExamples/validationSchema"
+import * as React from "react"
+import typographyStyles from "../../styles/typography.module.css"
+
+export default (
+ <>
+
Всем привет,
+
+ Вот критические изменения, которые вам необходимо отрегулировать. Мы
+ искренне надеемся эти изменения не создают особых проблем для вашего кода.
+ если ты Вам интересны некоторые из причин, вы можете взглянуть на это {""}
+
+ pull request
+ {" "}
+ Больше подробностей.
+
+
+
+ ❤️ React hook Form Team
+
+
+
+
+
+
+
+
useForm:
+
+
+
+ Мы удаляем префикс validation для всех настроек.
+
+
+
+
+
+
+
validationSchema:
+
+
+ validationSchema был заменен стандартным
+ resolver, и вы можете использовать Yup, Joi и Superstruct
+ на момент. У нас есть официальная библиотека преобразователей для
+ поддержки большего количества схем проверка в будущем.
+
+
+
+ npm install @hookform/resolvers
+
+
+
+
+
+
Controller:
+
+
+ Tornamos a API do Controller muito mais simples, e os
+ seguintes adereços foram removidos e substituídos por{" "}
+ render adereços.
+
>
),
types: (
<>
- This is useful for input validation like rules of password, which
- multiple errors need to return for a single field. To enable this
- feature, make sure you have set validateCriteriaMode: 'all'
- .
+ 这对于输入验证(例如密码规则)很有用, 需要为单个字段返回多个错误。为此
+ 功能,请确保已设置 criteriaMode 'all'.
>
),
message: `默认情况下消息是空字符串。 但是,如果您使用错误消息注册验证,那么它将被返回。`,
ref: `输入元素的参考。`,
+ note: (goToSection) => (
+
- React Hook Form 使用 input
+ React Hook Form 使用input
事件作为输入来响应。您可以轻松切换到
- fireEvent.input 用于react-testing-library。
+ fireEvent.input用于react-testing-library。
@@ -445,7 +445,7 @@ export default {
),
},
{
- title: "Controller not working with submitFocusError?",
+ title: "Controller not working with shouldFocusError?",
description: (
<>