React.js + Next.js
"Form submission canceled because the form is not connected" 오류
진호우
2024. 11. 21. 17:46
리액트에서 폼을 사용할 때 "Form submission canceled because the form is not connected"라는 오류가 발생할 수 있다. 이 오류는 <form> 태그가 올바르게 설정되지 않았거나 폼 제출 방식이 잘못 처리될 때 나타난다. 아래에서 주요 원인과 해결 방법을 정리한다.
1. onSubmit 이벤트 처리 문제
<form> 태그에서 브라우저의 기본 제출 동작이 막히지 않으면 이 오류가 발생할 수 있다.
해결 방법
onSubmit 이벤트에서 event.preventDefault()를 호출하여 기본 동작을 방지해야 한다.
const handleSubmit = (event: React.FormEvent) => {
event.preventDefault(); // 기본 제출 동작 방지
// 폼 제출 로직 작성
};
return (
<form onSubmit={handleSubmit}>
<input type="text" name="example" />
<button type="submit">Submit</button>
</form>
);
2. react-hook-form 사용 시 발생하는 문제
react-hook-form을 사용할 때, handleSubmit 함수 없이 네이티브 폼 제출 방식으로 처리하면 오류가 발생할 수 있다.
해결 방법
react-hook-form의 handleSubmit 함수를 사용하여 폼 제출을 처리해야 한다.
import { useForm } from 'react-hook-form';
const MyForm = () => {
const { register, handleSubmit } = useForm();
const onSubmit = (data: any) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('example')} />
<button type="submit">Submit</button>
</form>
);
};
3. <form> 태그가 DOM에 연결되지 않은 경우
<form> 태그가 실제로 DOM에 렌더링되지 않았거나, 조건부 렌더링 등에 의해 출력되지 않는 경우에도 이 오류가 발생할 수 있다.
해결 방법
- <form> 태그가 정상적으로 렌더링되는지 확인한다.
- 조건부 렌더링이 있는 경우, 렌더링 조건이 올바른지 점검한다.
const ConditionalForm = ({ showForm }: { showForm: boolean }) => {
if (!showForm) return null;
return (
<form onSubmit={(e) => e.preventDefault()}>
<input type="text" />
<button type="submit">Submit</button>
</form>
);
};
4. type="submit" 버튼 확인 (문제이유)
이번 문제의 원인과 해결방안이다.
폼 제출을 트리거하는 버튼에 type="submit"이 빠지거나 잘못 설정되어 있으면 오류가 발생할 수 있다.
해결 방법
<button> 요소에 type="submit"을 명시적으로 설정한다. 이번 경우는 type="button"을 명시적으로 표기
<form>
<button type="submit">Submit</button>
</form>