728x90

[React] input이 많을 경우
쇼핑몰 프로젝트를 만들던 중 새로운 제품을 등록할 때 input태그가 많이 필요했음
기존에 2개일경우 useState로 관리해 줬지만 input이 많아지니 일일이 관리해 줄 수 없었음
그래서 구글링을 해봄
구글링 결과 input태그에 name 속성을 지정한 후, 아래와 같이 {}, 객체 안에 name: value 형식으로 관리해 주면 됨
javascript
닫기 const [product, setProduct] = useState({});
setProduct({...product, [e.target.name]: e.target.value})
전체 코드
javascript
닫기import React, { useState } from "react";
function NewProduct(props) {
const [product, setProduct] = useState({});
const InputSubmit = (e) => {
e.preventDefault();
if (
!myData.img &&
!myData.title &&
!myData.price &&
!myData.gender &&
!myData.explanation &&
!myData.size
) {
console.log('수정된항목이없음')
} else{
console.log('정상', myData)
}
}
const onChangeInput = (e) => {
setProduct({...product, [e.target.name]: e.target.value})
}
return (
<div>
<form className='flex flex-col items-center ' onSubmit={InputSubmit}>
<input type='file' name='img' onChange={onChangeInput}/>
<input type='text' placeholder='제품명' onChange={onChangeInput} name='title' />
<input type='number' placeholder='가격'onChange={onChangeInput} name='price' />
<select name='gender' onChange={onChangeInput}>
<option value=''>성별</option>
<option value='male'>남자</option>
<option value='female'>여자</option>
</select>
<input type='text' placeholder='설명' onChange={onChangeInput} name='explanation' />
<select name='size' onChange={onChangeInput}>
<option value=''>사이즈</option>
<option value='S'>S</option>
<option value='M'>M</option>
<option value='L'>L</option>
<option value='XL'>XL</option>
</select>
<Button type='submit' text={'제품 등록하기'}>제품 등록하기</Button>
</form>
</div>
);
}
export default NewProduct;

이런식으로 나옴.
728x90
'TIL' 카테고리의 다른 글
142. [React] useNavigate로 state 넘기기 TIL23.03.14 (0) | 2023.03.14 |
---|---|
141. [CSS] opacity 와 filter: brightness() 차이 TIL 23.03.13 (0) | 2023.03.13 |
139. firebase database "setValue at ~ failed: DatabaseError: Permission denied" error TIL23.03.06 (0) | 2023.03.08 |
138. TIL23.03.07 (0) | 2023.03.07 |
137. [React] useEffect, console.log TIL23.03.06 (0) | 2023.03.06 |
댓글