본문 바로가기

React

react-hook-form을 이용한 인풋 컴포넌트 구현

 

https://kangcheon.tistory.com/95

 

인풋 컴포넌트 상태관리

https://kangcheon.tistory.com/94 재사용 위한 인풋 컴포넌트 버튼 컴포넌트에 이어서 이번엔 인풋태그 관련 컴포넌트를 만들어 보았다 시작하기 앞서 https://kangcheon.tistory.com/91 리액트 버튼 컴포넌트 재

kangcheon.tistory.com

https://kangcheon.tistory.com/94

 

재사용 위한 인풋 컴포넌트

버튼 컴포넌트에 이어서 이번엔 인풋태그 관련 컴포넌트를 만들어 보았다 시작하기 앞서 https://kangcheon.tistory.com/91 리액트 버튼 컴포넌트 재사용 간단하게 공통으로 사용할 버튼 태그를 만들어

kangcheon.tistory.com

 

위의 두 뻘짓으로 인해 react-hook-form 이라는 라이브러리를 알게 되었고 이놈을 사용하면,

커스텀훅도 상태관리 코드도 사용할 필요없이 그냥 react-hook-form의 커스텀 훅만 호출해주면 된다

(지금 생각해 봐도 상태관리까지 하는 건 투머치 인거 같긴 하다.. ㅋㅋ)

 

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

 

useForm

Performant, flexible and extensible forms with easy-to-use validation.

react-hook-form.com

이곳에서 더 자세한 정보를 확인 할 수 있다

 

사용을 위해 터미널에 설치 명령어를 입력하자

npm install react-hook-form

 

 

그리고 사용할 컴포넌트에서 useForm 훅을 불러오자, 그러면 여러가지 함수를 사용 할 수 있는데
그 중 내가 사용한 함수는 세 가지다

  • register : 이 함수의 인자로 id 값을 넣어주고 태그에 적용하면 useForm 관련 기능 사용 가능
  • handleSubmit : form 태그에서 발생하는 submit 이벤트 처리
  • reset : 각 상태값 초기화

USAGE

import { useForm } from 'react-hook-form';
import FormMain from './components/input/FormMain';

export default function FormHook() {
  const { register, handleSubmit, reset } = useForm({
    // 초기값 설정
    defaultValues: {
      username: '주니어네키',
    },
  });
  const onClickLoginBtn = (data) => {
    console.log(data);
  };
  return (
    <FormMain>
      <FormMain.Label htmlFor="username">아이디</FormMain.Label>
      <FormMain.Input id="username" registerFn={register('username')} />
      <FormMain.Label htmlFor="password">비밀번호</FormMain.Label>
      <FormMain.Input type="password" id="password" registerFn={register('password')} />
      <FormMain.Button text="로그인" type="submit" onClick={handleSubmit(onClickLoginBtn)} />
      <FormMain.Button text="초기화" onClick={() => reset()} />
    </FormMain>
  );
}

 

register 함수를 해당 컴포넌트의 프롭으로 내려주어 사용 가능하도록 하였다.

 

useForm을 사용해 내가 그렇게 애먹던 초기값도 편하게 값만 입력함으로써 할당해 줄 수 있다..!

이 기능은 input[type="text"] 뿐 아니라 다른 속성을 가진 인풋태그에서도 사용가능하다

 

그리고 handleSumit 안의 실행할 함수를 인자로 넣어주면 event.preventDefault() 코드를 작성하지 않아도
새로고침 되지 않는 것을 확인 할 수 있다.

 

input 컴포넌트

import divideStyleIDString from '../../../utils/divideStyleIDString';
import styles from '../style/InputCustom.module.css';

export default function InputFieldCustom({
  type = 'text',
  id,
  styleID,
  name,
  placeholder,
  defaultValue,
  registerFn,
  readOnly,
}) {
  if (type !== 'text' && type !== 'password') {
    throw new Error(`Invalid type '${type}' for InputButtonCustom. Type must be 'text' or 'password'.`);
  }
  return (
    <input
      id={id}
      type={type}
      name={name}
      {...registerFn}
      placeholder={placeholder}
      readOnly={readOnly}
      className={`${divideStyleIDString(styles, styleID)}`}
      aria-label={`inputTEXT_${id}`}
      aria-labelledby={id}
    />
  );
}

 

이전 포스팅의 코드와 달라진 점은 registerFn을 제외하곤 크게 없다

이렇게 react-hook-form 이라는 라이브러리를 사용 함으로써 굳이 쓸데없는 코드를 줄일 수 있게 되서 더 좋은 것 같다

 

위에서는 정말 간단한 사용법만 적어놓았지만 공식 문서를 들어가서 확인 해 보면 useForm 훅 뿐만 아니라 성능개선,에러처리 등등 상당히 많은 기능들을 제공하는 것을 알 수 있다