[react] 이미지 선택 Input 에서 라벨을 눌러도 파일 선택 창이 나오는 현상 수정

새결·2023년 9월 17일
0

project-bbangorder

목록 보기
4/4

원래는 위처럼 파일 선택 버튼과 선택된 파일 없음이라는 라벨? 이 자동으로 나왔었다.
그러나 저 라벨을 누르면 이미지 선택 창이 나오는 부분이 불편하다고 피드백을 받았다.

원래의 코드는 아래와 같다.

import React, { useRef, useState } from 'react';
import axios from 'axios';
import { Modal, ModalOverlay } from '../../assets/Modal.jsx';
import Button from '../../assets/buttons/Button.jsx';
import { CancelButton } from './EditProfile.jsx';
import { useAuthStore } from '../../store/store.js';

const ImageUploadModal = ({ onClose }) => {
  const inputRef = useRef(null);

  const [preview, setPreview] = useState(null);

  const accessToken = useAuthStore((state) => state.accessToken);

  const handleUpload = async (event) => {
    event.preventDefault();

    const formData = new FormData();
    formData.append('file', inputRef.current.files[0]); // input 태그를 통해 사용자가 선택한 첫 번째 파일

    try {
      await axios.post(
        `${process.env.REACT_APP_API_URL}/api/member/image`,
        formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data',
            Authorization: `Bearer ${accessToken}`,
          },
        },
      );

      alert('이미지가 성공적으로 업로드되었습니다.');
      window.location.reload();
    } catch (error) {
      console.error('이미지 업로드 실패:', error);
    }
  };

  const handlePreview = (event) => {
    const file = event.target.files[0];
    const reader = new FileReader();

    reader.readAsDataURL(file);
    reader.onloadend = () => {
      setPreview(reader.result);
    };
  };

  return (
    <>
      <ModalOverlay onClick={onClose} />
      <Modal>
        <form
          className="flex flex-col justify-center items-center gap-4"
          onSubmit={handleUpload}
        >
          <div className="w-64 h-64 border-2 border-black-100">
            {preview && (
              <img className="w-full h-full" src={preview} alt="미리보기" />
            )}
          </div>
          <input
            className="w-2/3"
            type="file"
            ref={inputRef}
            onChange={handlePreview}
          />
          <div className="flex gap-4">
            <Button type="submit">업로드</Button>
            <CancelButton type="button" onClick={onClose}>
              닫기
            </CancelButton>
          </div>
        </form>
      </Modal>
    </>
  );
};

export default ImageUploadModal;

여기서 input 를 화면상 안보이게 하고 커스텀 버튼을 추가해서 input 의 기능을 하게 하기로 했다.

우선 기존의 ref를 활용해 함수를 만들었다.

const handleFileClick = () => {
  inputRef.current.click();
};

그리고 커스텀 버튼을 추가했다.

<Button type="button" onClick={handleFileClick}>
  이미지 선택
</Button>

이렇게 하면 해당 버튼이 이미지 업로드 하는 기능과 똑같아졌다.

아래는 결과다!

profile
프론트엔드 개발자

0개의 댓글

관련 채용 정보