본문 바로가기

개발자 페이지/React JS, Next JS

React /Typescript: react-hook-form 세팅

728x90
반응형

React JS에는 react-hook-form 이라는 library를 사용할 수 있다.

form 태그에서 input 값이 많아지면 관리가 까다로워 지는데 그런 번거로움을 도와주는 유용한 기능이다.

 

 

터미널에서 아래와 같이 설치하고 

npm install react-hook-form

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

위 링크로 가면 스타트 가이드라인이 있으니 자세한 내용 확인.

 

아래 코드는 react-hook-form 활용을 위한 초기 세팅 코드이다.

1.useForm 을 react-hook-form에서 가져온다.

2. ToDoList 함수에 {register, handleSubmit, setValue}갑을 useForm으로 부터 가져온다.

3. form 태그에 onsubmit을 적용, handleSubmit를 호출한후 괄호안에 사용자 함수를 넣는다 

    <form onSubmit={handleSubmit(handleValid)}>   *handleSubmit은 useForm 함수

4. input 태그에는 {...register("toDo")}로 register값에서 사용할 모든 값을 가져온다.

5. Typescript 에는 데이터 변수가 없으면 error를 가져오기 때문에 interface IForm을 통해서 "toDo" 변수가 string이라는 것을 명시하고 useForm<IForm>으로 불러오고 직접 작성한 함수에도

data: IForm 값을 넣어준다.

import { useForm } from "react-hook-form";

interface IForm {
  toDo: string;
}

function ToDoList() {
  const { register, handleSubmit, setValue } = useForm<IForm>();
  const handleValid = (data: IForm) => {
    console.log("add to do ", data.toDo);
    setValue("toDo", "");
  };
  return (
    <div>
      <form onSubmit={handleSubmit(handleValid)}>
        <input
          {...register("toDo", { required: "Please write a To Do" })}
          placeholder="Write a to do"
        />
        <button>Add</button>
      </form>
    </div>
  );
}

export default ToDoList;

 

728x90