본문 바로가기
Aaron[에런]/코드 스니펫

[React Custom Hooks] Form hooks ver 0.1 (with TypeScript)

by Aaron-Kim 2022. 4. 21.

영상을 참고하여 직접 Form 관련 커스텀 훅을 간단히 제작해보았습니다.

아직 미숙한 부분이나 부족한 점이 많지만,

실무, 사이드 프로젝트 등 여러 경험들을 토대로 저만의 커스텀 훅을 더 잘 보완해나가겠습니다.

 

// form-hooks.ts
import React, { useCallback, useState } from 'react';

export interface IuseInputProps {
  type: string;
  defValue: string | number;
}

const useInput = ({ type, defValue }: IuseInputProps) => {
  const [value, setValue] = useState(defValue);
  return {
    inputProps: {
      type,
      value,
      onChange: useCallback((event: React.FormEvent<HTMLInputElement>) => {
        setValue(event.currentTarget.value);
      }, []),
    },
    resetFn: () => {
      setValue(defValue);
    },
  };
};

export { useInput };
// HooksTest.tsx
import { FormEvent } from 'react';
import { useInput } from './form-hooks';

const HooksTest = () => {
  const { inputProps: idInput, resetFn: resetIdInput } = useInput({
    type: 'text',
    defValue: '',
  });
  const { inputProps: passwordInput, resetFn: resetPasswordInput } = useInput({
    type: 'password',
    defValue: '',
  });
  const {
    inputProps: passwordConfirmInput,
    resetFn: resetPasswordConfirmInput,
  } = useInput({
    type: 'password',
    defValue: '',
  });
  const { inputProps: emailInput, resetFn: resetEmailInput } = useInput({
    type: 'email',
    defValue: '',
  });
  const { inputProps: telInput, resetFn: resetTelInput } = useInput({
    type: 'tel',
    defValue: '',
  });

  const onSubmit = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    resetIdInput();
    resetPasswordInput();
    resetPasswordConfirmInput();
    resetEmailInput();
    resetTelInput();
  };

  return (
    <form
      onSubmit={onSubmit}
      style={{
        width: '100%',
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
      }}
    >
      <label>
        <span>ID </span>
        <input {...idInput} autoFocus required />
      </label>
      <br />
      <label>
        <span>비밀번호 </span>
        <input {...passwordInput} required />
      </label>
      <br />
      <label>
        <span>비밀번호 확인</span>
        <input {...passwordConfirmInput} required />
      </label>
      <br />
      <label>
        <span>이메일 </span>
        <input {...emailInput} required />
      </label>
      <br />
      <label>
        <span>전화번호 </span>
        <input {...telInput} required />
      </label>
      <br />
      <button>저장</button>
    </form>
  );
};

export default HooksTest;

[Github gist] - form-hooks.ts (ding-co)

[참고 영상] 시니어코딩 (유튜브) - React 이론 11강. Custom Hook

반응형

댓글