[HTML] Form 내부의 Button 클릭 시 자동으로 Submit되는 현상

Janet·2023년 12월 14일
0

HTML

목록 보기
1/1

form 요소 안에 button이 있을 때, 자동으로 원치않는 타이밍에 Submit이 되는 경우가 있다. 간단한 문제이지만 잊고있다가 뭐가 문제지 하고 헤맸다...🥲

Form이 Submit 되어야 하는 순간은 ‘Create’버튼이 눌렸을 때 인데, 그 전에 별도의 버튼이 있는 경우 이런 현상이 발생했는데 이런 경우 다음과 같이 Submit을 막을 버튼의 타입을 button으로 명시해주면 된다.

<button type="button">버튼</button>

예시 코드

수정 전: Color 버튼을 클릭할 경우 Submit이 일어났다.

<form onSubmit={handleSubmit}>
  <label>Name</label>
  <input type="text" onChange={handleNameChange} />
  <label>Cover</label>
    {colors.map((color, index) => (
      // Submit이 일어나는 구간 
      <button
        key={index}
        onClick={() => handleColorChange(color, index)}
      >{color}
      </button>
    ))}
  <button>Create</button>
</form>

수정 후: Create 버튼을 클릭할 경우 Submit이 일어난다.

<form onSubmit={handleSubmit}>
  <label>Name</label>
  <input type="text" onChange={handleNameChange} />
  <label>Cover</label>
    {colors.map((color, index) => (
      <button
        key={index}
        type="button" // button의 타입 정의
        onClick={() => handleColorChange(color, index)}
      >
      </button>
    ))}
  <button>Create</button>
</form>
profile
😸

0개의 댓글