본문 바로가기
프로그래밍/React

[React] 이미지 업로드 및 미리보기

by YuminK 2023. 9. 9.

초기 이미지 태그의 src에 넣을 state값을 정의하고 onChange 함수를 만든다. (이미지 데이터 변경시 사용)

  const [preview, setPreview] = useState("img/book3.jpg");

  const onChange = (e) => {
    const img = e.target.files[0];
    console.log(img);

    var reader = new FileReader();
    reader.readAsDataURL(img);
    reader.onload = function (e) {
      setPreview(e.target.result);
    };
  };

 

사용하는 곳에 preview로 연결하면 된다.

      <div className="profile-img-wrapper">
        <img src={preview} />
      </div>

      <div style={{ marginTop: 4 }} />
      <input
        type="file"
        accept="image/*"
        name="profileImg"
        onChange={onChange}
      />

 

CSS 부분(정사각형 모양)

/* image wrapper */
.profile-img-wrapper {
  position: relative;
  width: 200px;
  height: 200px;
}

.profile-img-wrapper img {
  position: absolute;
  top: 0;
  left: 0;
  transform: translate(50, 50);
  width: 100%;
  height: 100%;
  object-fit: cover;
  margin: auto;
}

 

결과

 

 

추가) 버튼 커스텀하기

input 부분을 가려주고 htmlFor 태그를 사용하면 된다. 

<input
type="file"
name="file"
id="file"
accept="image/*"
onChange={onChange}
style={{ display: "none" }}
/>

 

<label htmlFor="file"><div> aaa </div> </label>

'프로그래밍 > React' 카테고리의 다른 글

[React] useRef  (0) 2023.11.28
[React] useEffect  (0) 2023.11.28
[React] useState  (0) 2023.11.27
[React] 리액트 개요  (0) 2023.11.27
[React] 페이지 이동하기  (0) 2023.09.06

댓글