Learning Log/React

[react] input 태그로 이미지 업로드하기

자척개 2023. 3. 9. 20:04
반응형
import { useRef, useState } from "react";
import "./styles.css";

export default function App() {
  const [image, setImage] = useState(null);
  const inputRef = useRef(null);

  const 이미지넣기 = () => {
    if (!inputRef.current) return;
    inputRef.current.click();
  };

  const 이미지변경됐을때_실제스테이트에_넣는함수 = ({ target: { files } }) => {
    setImage(files[0]);
  };

  const 전송해보자 = () => {
    const formData = new FormData();
    formData.append("image", image);

    for (let [key, value] of formData.entries()) {
      console.log(key, value);
    }
  };

  return (
    <div className="App">
      <div className="dropzone">
        {image ? (
          <img src={URL.createObjectURL(image)} alt="test" />
        ) : (
          <h1 className="pointer" onClick={이미지넣기}>
            이미지없으니까 여기 눌러라
          </h1>
        )}
        <input
          ref={inputRef}
          type="file"
          hidden
          accept="image/*"
          onChange={이미지변경됐을때_실제스테이트에_넣는함수}
        />
      </div>

      <h2>Start editing to see some magic happen!</h2>
      <button onClick={전송해보자}>전송해보자!!!!!!</button>
    </div>
  );
}

 

Resources

윤국멘토님💻

반응형