form

사용 방법

  1. 초기 폼 데이터 생성 - src/constants/init-form-data.ts 파일에 페이지 이름을 key 값으로 하는 object 추가 - object의 key 값은 각각의 컴포넌트의 name 값으로 입력 - 모든 value 값은 string 형태로 입력 (array일 경우 콤마로 구분된 string)

src/constants/init-form-data.ts
interface initFormDataType {
  [key: string]: {
    [key: string]: string
  }
}

export const initFormData: initFormDataType = {
  samplePage: {
    a: 'aaa',
    b: 'bbb',
    c: 'ccc',
  },
  adminAccountList: { // 관리자 관리 - 계정 관리 - 목록
    searchType: 'username',
    searchText: '',
    sortType: 'date-desc',
    pageNo: '1',
    pageSize: '20',
  },
  adminAccountCreate: { // 관리자 관리 - 계정 관리 - 등록
    id: '',
    password: '',
    passwordCheck: '',
    isActive: 'false',
    selectDate: '',
    fromDate: '',
    toDate: '',
    radioGroup: '비과세',
    checkGroup: '',
    singleSelect: '',
    multiSelect: '',
    isOpen: 'false',
    authority: '',
    name: '',
    phoneNumber: '',
    email: '',
  },
}
  1. 위에서 설정한 initFormData를 import하고, useForm 커스텀 훅을 통해 formData 및 handleFormChange, resetForm 생성

pages/sample-page.tsx
import { initFormData } from '@/src/constants'
import { createPageForm, useForm } from '@/src/hooks/use-form'

export default function SamplePage() {
  const { formData, handleFormChange, resetForm } = useForm(initFormData.samplePage)

  return (
    <InputBox
      name={'a'}
      placeholder={'6자리 이상 12자리 이하'}
      value={'aaa'}
      onChange={() => {}}
    />
  )
}

3. 하위 컴포넌트에 props로 전달

pages/sample-page.tsx
import { initFormData } from '@/src/constants'
import { createPageForm, useForm } from '@/src/hooks/use-form'

export default function SamplePage() {
  const { formData, handleFormChange, resetForm } = useForm(initFormData.samplePage)

  return (
    <InputBox
      name={'a'}
      placeholder={'6자리 이상 12자리 이하'}
      value={formData['a']}
      onChange={handleFormChange}
    />
  )
}
  1. 하위 컴포넌트에서 formData 변경

components/ui/input-box.tsx
export function InputBox({
  type = 'text',
  name,
  value,
  placeholder,
  subMessage,
  onChange,
}: InputBoxProps) {
  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    // onChange에는 { key: value } 형태의 object를 넘겨줌
    // key 값은 name, value는 변경할 값 
    onChange({
      [name]: e.target.value
    })
  }
    
  return (
    <Input
      name={name}
      value={value}
      onChange={handleChange}
    />
  )
}

Last updated