[React] Upload an image

Suyeon·2020년 9월 21일
0

React

목록 보기
2/26

Upload and display an image on UI

const Component = () => {
   const [imgUrl, setImgUrl] = useState();
  
   const handleChangeImg = e => {
   const file = e.target.files[0];
   const reader = new FileReader();

   reader.onloadend = finishedEvent => {
     const result = finishedEvent.currentTarget.result;
     setImgUrl(result);
   };

   reader.readAsDataURL(file);
 };

 const handleDeleteImg = () => setImgUrl(null);
  
 return(
   <input type="file" accept="image/*" onChange={`handleChangeImg`} />
          {imgUrl && (
            <div>
              <img src={imgUrl} width="50px" height="50px" alt="Tweet" />
              <button onClick={handleDeleteImg}>Clear</button>
            </div>
          )}
   );
}
profile
Hello World.

0개의 댓글