분류 Reactjs

React Hook 양식

컨텐츠 정보

  • 조회 719 (작성일 )

본문

사용하기 쉬운 검증 기능을 갖춘 유연하고 확장 가능한 성능의 양식.


https://react-hook-form.com/ 


설치 


React Hook Form을 설치하는 데는 단일 명령만 사용하면 준비가 완료됩니다.


npm install react-hook-form 


 


다음 코드는 기본 사용법을 보여줍니다.


import React from 'react'
import useForm from 'react-hook-form'

export default function App() {
  const { register, handleSubmit, watch, errors } = useForm()
  const onSubmit = data => { console.log(data) }

  console.log(watch('example')) // watch input value by passing the name of it

  return (
    {/* "handleSubmit" will validate your inputs before invoking "onSubmit" */}
    <form onSubmit={handleSubmit(onSubmit)}>
    {/* register your input into the hook by invoking the "register" function */}
      <input name="example" defaultValue="test" ref={register} />
      
      {/* include validation with required or other standard HTML validation rules */}
      <input name="exampleRequired" ref={register({ required: true })} />
      {/* errors will return when field validation fails  */}
      {errors.exampleRequired && <span>This field is required</span>}
      
      <input type="submit" />
    </form>
  )
}

비디오 튜토리얼 


이 비디오 자습서에서는 React Hook Form 사용의 기본 사용법과 개념을 설명했습니다.



필드 등록 


React Hook Form의 핵심 개념 중 하나는 제어되지 않은 구성 요소를 Hook에 등록하여 제출을 위해 해당 값을 확인하고 수집 할 수 있도록 하는 것입니다.


참고 : 각 필드에는 등록 프로세스의 키로 고유 한 이름이 있어야 합니다.


참고 : React Native는 수동 등록 명령을 사용해야 합니다 (예 : register ({name : 'test'}, {required : true})


import React from 'react'
import useForm from 'react-hook-form'

export default function App() {
  const { register, handleSubmit } = useForm()
  const onSubmit = data => console.log(data)
   
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input name="firstName" ref={register} />
      <select name="gender" ref={register}>
        <option value="male">male</option>
        <option value="female">female</option>
      </select>
      <input type="submit" />
    </form>
  );
}

유효성 검사 적용 


React Hook Form은 기존 HTML 표준 양식 유효성 검사에 따라 양식 유효성 검사를 쉽게 만듭니다.


다음에서 지원되는 유효성 검사 규칙 목록 :


  • required
  • min
  • max
  • minLength
  • maxLength
  • pattern
  • validate

레지스터 섹션에서 각 규칙에 대한 자세한 내용을 읽을 수 있습니다.


import React from 'react'
import useForm from 'react-hook-form'

export default function App() {
  const { register, handleSubmit } = useForm()
  const onSubmit = data => console.log(data)
   
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input name="firstName" ref={register({ required: true, maxlength: 20 })} />
      <input name="lastName" ref={register({ pattern: /^[A-Za-z]+$/i })} />
      <input name="age" type="number" ref={register({ min: 18, max: 99 })} />
      <input type="submit" />
    </form>
  );
}

기존 양식 적응 


기존 양식 작업은 간단합니다. 중요한 단계는 레지스터를 기존 구성 요소의 참조에 적용하는 것입니다.


import React from 'react'
import useForm from 'react-hook-form'

// The following component is an example of your existing Input Component 
const Input = ({ label, register, required }) => ( 
  <>
    <label>{label}</label>
    <input name={label} ref={register({ required })} />
  </>
)

// you can use React.forwardRef to pass the ref too
const Select = React.forwardRef(({ label, register }, ref) => ( 
  <>
    <label>{label}</label>
    <select name={label} ref={ref}>
      <option value="20">20</option>
      <option value="30">30</option>
    </select>
  </>
))

export default function App() {
  const { register, handleSubmit } = useForm()
  const onSubmit = data => console.log(data)
   
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Input label="First Name" register={register} required />
      <Select label="Age" ref={register} />
      <input type="submit" />
    </form>
  )
}

UI 라이브러리 작업 


React Hook Form을 사용하면 외부 UI 구성 요소 라이브러리와 쉽게 통합 할 수 있습니다.


참고 : 대부분의 UI 라이브러리는 innerRef 또는 ref를 등록하도록 노출합니다. react-select 또는 react-datepicker와 같이 복잡한 컴포넌트의 경우 setValue를 통해 값을 수동으로 업데이트하거나 setError로 오류를 트리거 할 수 있습니다.


import React from 'react';
import useForm from 'react-hook-form';
import Select from "react-select";
import Input from "@material-ui/core/Input";
import { Input as InputField } from 'antd';

export default function App() {
  const { register, handleSubmit, setValue } = useForm();
  const onSubmit = data => console.log(data);
  const [values, setReactSelectValue] = useState({ selectedOption: [] });

  const handleMultiChange = selectedOption => {
    setValue("reactSelect", selectedOption);
    setReactSelectValue({ selectedOption });
  }
  
  const handleChange = (e) => {
    register({ name: "AntdInput" }, e.target.value);
  }
  
  React.useEffect(() => {
    register({ name: "reactSelect" }); // custom register react-select 
    register({ name: "AntdInput" }); // custom register antd input
  }, [register])

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Input name="HelloWorld" inputRef={register} />
      <InputField name="AntdInput" onChange={handleChange} />
      <Select
        value={values.selectedOption}
        options={options}
        onChange={handleMultiChange}
        isMulti
      />
      <input type="submit" />
    </form>
  );
}

글로벌 상태 통합 


React Hook Form에는 데이터를 저장하기 위해 상태 관리가 필요하지 않지만 쉽게 관리 할 수 ​​있습니다.


import React from 'react'
import useForm from 'react-hook-form'
import { connect } from 'react-redux'
import updateAction from './actions'

export default function App(props) {
  const { register, handleSubmit, setValue } = useForm()
  // Submit your data into Redux store
  const onSubmit = (data) => props.updateAction(data)
  
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Input name="firstName" defaultValue={props.firstName} ref={register} />
      <Input name="lastName" defaultValue={props.lastName} ref={register} />
      <input type="submit" />
    </form>
  );
}

// Connect your component with redux
connect(({ firstName, lastName }) => ({ firstName, lastName }), updateAction)(YourForm)

오류 처리 


React 후크 양식은 양식 내의 오류를 표시하기 위해 오류 개체를 제공합니다.


import React from 'react'
import useForm from 'react-hook-form'

export default function App() {
  const { register, errors } = useForm()
  
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Input name="firstName" ref={register({ required: true })} />
      {errors.firstName && 'First name is required'}
      <Input name="lastName" ref={register({ required: true })} />
      {errors.lastName && 'Last name is required'}
      <input type="submit" />
    </form>
  );
}

코드 예 


React Hook Form은 API를 단순화하여 최상의 DX 제공에 중점을 둡니다.


useForm: Function 


useForm을 호출하면 register, unregister, errors, watch, handleSubmit, reset, setError, clearError, setValue, getValues, triggerValidation 및 formState 메소드가 수신됩니다.


useForm에는 선택적 인수도 있습니다. 다음 예제는 모든 옵션의 기본값을 보여줍니다.


const { register } = useForm({
  mode: 'onSubmit',
  reValidateMode: 'onChange',
  defaultValues: {},
  validationFields: [],
  validationSchema: {},
  validationSchemaOption: { abortEarly: false },
  submitFocusError: true,
  nativeValidation: false,
})