Archive

[TIL220128] Image uploader

manon_e 2022. 1. 28. 04:12
반응형

 

 

 



const ImageUpload = ({ title }) => {
  const [selectedFile, setSelectedFile] = useState([]);

  const fileInput = useRef();

  const fileSelectedHandler = (e) => {
    const fileName = e.target.files[0].name;
    window.localStorage.setItem(fileName, fileName);
    const addImg = () => {
      let imageArr = [...selectedFile];
      imageArr.unshift(fileName);
      setSelectedFile(imageArr);
    };
    addImg();

  };

  const addImgBtn = (e) => {
    e.preventDefault();
    fileInput.current.click(); //onchange아니고 click!!!!
  };

  const removeImgBtn = (e) => {
    setSelectedFile(selectedFile.filter((name) => name !== e));
    window.localStorage.removeItem(e);
  };

//
    <div className="container">
      <div className="title">
        <h2>{title} 이미지</h2>
      </div>
      <div className="imgAddContainer">
        <input
          type="file"
          style={{ display: "none" }}
          onChange={fileSelectedHandler}
          ref={fileInput}
        />
      ...

 

 

 

 

 

반응형

'Archive' 카테고리의 다른 글

[Next.JS] Dynamic Routes  (0) 2022.02.15
[Redux] Redux & Redux-toolkit  (0) 2022.02.13
[TIL220127] localStorage  (0) 2022.01.28
[React] React 동작원리 ( + useMemo / useCallback )  (0) 2022.01.27
[TIL220126] Prettier 설정  (0) 2022.01.27