HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
💌
JJong’s Archive
/
⚽
공용 Component
/
upload 커스텀 컴포넌트 만들기

upload 커스텀 컴포넌트 만들기

태그
Dec 14, 2023
input 태그의 type 속성으로 file을 주면, 업로드를 할 수 있다.
  1. 파일을 상태로 관리
  1. <div><input type=”file”/></div>
  1. input은 display:none으로 가려주기
  1. useRef를 이용해 div를 클릭 시 input이 클릭되게 하기
  1. input의 onChange 속성을 통해 파일 선택 시 해당 파일을 상태로 set
const Input = styled.input` display: none ` const Upload({children, ...}) { const [file, setFile] = useState(null) const inputRef = useRef(null) const handleFileChange = (e) => { setFile(e.target.files[0]) } const handleClick = () => { inputRef.current.click() } <div onClick={handleClick}> <Input ref={inputRef} type="file" onChange={handleFileChange} ... /> {children} //Input이 안보이기 때문에 해당 자식만 보일것임 </div> }
 
 
참고) upload 컴포넌트의 자식을 받아와서, 해당 자식이 함수라면 함수를 실행하는 방식이 있다.
  • 여기서는 버튼 컴포넌트를 file이 있다면 button의 텍스트를 해당 파일 이름으로, 없다면 기본 이름으로 설정하는 함수를 자식으로 설정할 수 있다
<Upload> {(file) => <button>file ? file.name : "Click me!"</button>} </Upload>
<div> <Input /> {typeof children === "function" ? children(file): children} </div>
Upload.js
 
 

 
드래그 앤 드랍으로 업로드하도록 하기
  1. droppable를 props로 받고, dragging을 상태로 관리
notion image
  1. 드래그 들어왔을 때, 떠났을 때 이벤트 함수 만들기
notion image
  1. 전파를 막아줘야 하는 dragover와 파일을 내려놨을 때 이벤트 함수 만들기
notion image
  1. 컨테이너에 콜백 함수 등록
notion image
  1. Input의 children을 children(file, dragging) 으로 호출하기
  1. Upload를 호출할 때 자식의 스타일을 dragging에 따라 바꾸도록 해서 드래그 인 할 때 시각화하기
    1. notion image