⛵ 항해99/TIL · WIL ✏️

[TIL] 2023.10.21 - useRef(input 파일창 - div 연동)

hhhhy 2023. 10. 22. 17:39

 useRef 사용해서 input 파일창과 div 연동 

  • input은 숨김 처리
  • input / div 연결(useRef) →  div 클릭하면 input이 실행됨!
// ref 변수를 생성(input - div 연결)
const inputRef = useRef(null);


// div를 클릭 함수
const onClickHandler = () => {
  inputRef.current.click(); // input이 클릭됨 => 파일 선택창(inputSelectHandler) 열림
};


// inputSelectHandler
const inputSelectHandler = (e) => {
  const selectFile = e.target.files[0]; // 선택된 파일 가져오기
  console.log(`선택된 파일 이름: ${selectFile.name}`);
  console.log(`선택된 파일 크기: ${selectFile.size} bytes`);
};


// input(파일 선택창)
<input
  type="file" // 파일 선택할 수 있는 input 설정
  accept="image/*" // 이미지 파일만 선택 가능하게 설정
  onChange={inputSelectHandler} // 파일 선택 시 uploadImageHandler 함수가 실행
  className="hidden" // input 숨기기
  ref={inputRef} // input 연결하기 위해 ref를 사용
/>


// div
<div onClick={onClickHandler}>
  앨범에서 선택
</div>