728x90
여러장 이미지 업로드
const [showImg, setShowImg] = useState([]);
(...)
function handleAddImg(e){ //이미지 업로드 preview
const imgList = e.target.files;
let imgUrlList = [...showImg];
for(let i = 0; i < imgList.length; i++){
const currentImgUrl = URL.createObjectURL(imgList[i]);
imgUrlList.push(currentImgUrl);
}
if(imgUrlList.length > 6){ //최대 이미지 갯수 설정
imgUrlList = imgUrlList.slice(0, 6);
}
setShowImg(imgUrlList);
}
function handleDeleteImg(image){ //이미지 삭제
setShowImg(showImg.filter((it)=> it !== image ));
}
(...)
<label htmlFor='img' className='addImg' ><span class="material-symbols-outlined">
add_a_photo
</span></label>
{showImg.map((image, idx)=>(
<div key={idx} className='imgBox'>
<img src={image} alt={`img${idx}`} />
<button onClick={()=>handleDeleteImg(image)}><span class="material-symbols-outlined">
delete
</span></button>
</div>
))}
<input id='img' style={{display:'none'}} type='file' accept='/image/*' multiple onChange={handleAddImg}/>
input은 display:none을 하고 label에 디자인 요소를 넣으면 업로드 버튼을 꾸밀 수 있다.
input에 multiple 속성을 넣어야 여러장을 추가할 수 있다.
'Study > React' 카테고리의 다른 글
[React] 카카오 지도 API 가져오기 (5) | 2024.09.26 |
---|---|
[React] 공공데이터 포털 오픈 API 호출하기(+Axios 라이브러리) (0) | 2024.09.26 |
[React] Firebase로 앱 배포하기 (0) | 2024.08.07 |
[React/Next.js] 스와이퍼(swiper) 컨트롤러 커스텀하기 (0) | 2024.08.02 |
[React] next.js onClick 이벤트로 매개변수 함수 불러오기 (0) | 2024.08.01 |