어쩌다 알게 된 ƪ(•̃͡•̃͡ ƪ

[React] useFormik() 훅 본문

개발/🟦 React

[React] useFormik() 훅

비니_ 2025. 4. 10. 19:16
728x90

 

 

const customRestForm = useFormik({
  initialValues: {
    id: 0,
    companyId: company.get.id,
    type: 'REST_CUSTOM',
    name: null,
    memo: null,
  },
  // ... (validation, onSubmit 같은 나머지 설정도 있을 수 있어)
});

 

📌 useFormik() 훅 이란?

=> 폼 데이터를 관리하는 커스텀 객체

=>  React에서 폼을 쉽게 만들고 관리할 수 있게 도와주는 오픈소스 라이브러리

 

사용방법

// npm
npm install formik

// yarn
yarn add formik
import { useFormik } from 'formik';

 

 

✔ initialValues 

=> 초기 상태, 즉 처음 렌더링될 때 폼 안에 들어갈 기본 값

initialValues: {
  id: 0,
  companyId: company.get.id,
  type: 'REST_CUSTOM',
  name: null,
  memo: null,
}

 

return 값에서 사용시 아래처럼 주면 폼의 값 수정 가능

ex) 휴가 사유 수정

customRestForm.resetForm(); // customRestFrom 초기화
customRestForm.setValues({ // customRestFrom 값을 vacation 값으로 변경
  ...vacation,
});


// 사용 예시
return (
    <Button
      type='button'
      onClick={() => {
        customRestForm.resetForm();
        customRestForm.setValues({
          ...vacation,
        });
      }}>
      {수정 버튼}
    </Button>
)

 

✔ validate 

=> 에러 띄우기

=> 폼 입력값을 검사해서, 문제가 있으면 에러 메시지를 반환하는 함수

validate: (values) => {
    const errors = {};

    console.log('values', values);

    if(values.name === null){
        errors.name = '휴가 설정 이름이 필요합니다.';
    }
}

=> 오류가 있는 필드는 자동으로 errors 객체에 담김

 

✔ onSubmit 

=> 폼이 제출됐을 때 실행되는 함수

=> 보통 서버로 데이터를 전송하는 로직을 작성

onSubmit: async (values) => {
  console.log('onsubmit values>>>>', values);

  try {
    await axios.post('/api/vacation', values);
    alert('제출 완료!');
  } catch (error) {
    console.error('제출 실패', error);
  }
}

ex) 서버에 저장

728x90
Comments