
์
๊ทธ๋ ์ด๋๋ ์์
์ ์ํด
์ด๋ฏธ์ง ์
๋ก๋๋ฅผ ๋ฏธ๋ฆฌ๋ณด๊ธฐ / ์ญ์ ๊น์ง ๊ตฌํํ๋ ๋ฐฉ๋ฒ์ ์์๋ณด๋๋ก ํ๋ค!
์ด ๋ชจ๋ ๊ฒ์ ๋์ ๋น๋์
์ด ๋ ๊ฒ์ด์ผ... ๐
๊ตฌํํ๊ธฐ
- ํ์ผ์ ์ ๋ก๋ํ input ๋ฒํผ / ์ฌ๋ฆฐ ํ์ผ์ ์ด๋ฏธ์ง ๋ฏธ๋ฆฌ๋ณด๊ธฐ
- FileReader๋ฅผ ์ ์ธํ์ฌ ์ ๋ก๋ํ ํ์ผ ๊ฐ์ฒด๋ฅผ ๋ณ์์ ๋ด์.
- console.log(e.target.files);๋ฅผ ํ๊ฒ ๋๋ฉด,
์ ์ฌ์ง๊ณผ ๊ฐ์ด ๊ฐ์ฒด๋ก ๋ด๊ธด๋ค(์ฐธ๊ณ : FileList) - ๊ทธ๋ฌ๋ฉด e.target.files[0]์ผ๋ก ์ํ๋ ํ์ผ์ ๊ฐ์ ธ์ฌ ์๊ฐ ์๋ค.
- ๊ทธ ํ์ผ์ readAsDataURL๋ก ํ์ผ์ url์ ์ฝ์ด์จ๋ค.
- ์ ๋ก๋๊ฐ ๋๋ฉด imgSrc์ ํ์ผ์ ์ปจํ ์ธ ๊ฐ ์ ์ฅ์ด ๋๊ณ , ๊ทธ imgSrc๋ฅผ ์ด๋ฏธ์งํ๊ทธ์ ๋๊ฒจ์ฃผ์ด ์ด๋ฏธ์ง ๊ฒฝ๋ก๋ฅผ ๊ฐ์ ธ์ฌ ์ ์๋๋ก ํด์ค๋ค.
const [imgSrc, setImgSrc] = useState(null);
const onUpload = (e) => {
const file = e.target.files[0];
console.log(e.target.files);
const reader = new FileReader();
reader.readAsDataURL(file);
return new Promise((resolve) => {
reader.onload = () => {
setImgSrc(reader.result);
resolve();
};
});
};
...
return (
<input
accept="image/*"
multiple type={"file"}
onChange={(e) => onUpload(e)}
/>
<img
width={"300px"}
src={imgSrc}
alt=" "
/>
)
์ฌ์ง์ด ์์ ๋ ๋ทฐ
- public ํด๋์ ๋น ์ฌ์ง์ ๋ฃ๊ณ (blank.png) ์ผํญ์ฐ์ฐ์๋ฅผ ์ด์ฉํ๋ค.
<img src={imgSrc ? imgSrc : process.env.PUBLIC_URL + "blank.png"}/>
์ ๋ก๋ํ ์ฌ์ง ์ญ์
- ๋ฒํผ์ ํ๋ ๋ง๋ค์ด ๋ฒํผ์ ๋๋ฅด๋ฉด ์ญ์ ๊ฐ ๋๋๋ก ํ๋ค.
const onDelete = (e) => {
setImgSrc(null);
};
<button onClick={onDelete}>์ญ์ ํ๊ธฐ</button>

๊ทผ๋ฐ ์ด๋ ๊ฒ ํ๋๋ ์ญ์ ์์ ์ด๋ฆ์ด ๊ฐ์ด ์ง์์ง์ง๊ฐ ์์๋ฐ ใ
ใ
๊ทธ๋์ useRef ๋ฅผ ์ฌ์ฉํด์ฃผ์์!!!
const fileInput = useRef();
const onDelete = (e) => {
setImgSrc(null);
fileInput.current.value = "";
};
...
<input
accept="image/*"
multiple
type={"file"}
ref={fileInput}
onChange={(e) => onUpload(e)}
/>
useRef ๋ฅผ ์ด์ฉํด ํด๋น value๋ก ์ด๋ํด ๋ฐ๋ก ๋น๊ฐ์ผ๋ก ๋ง๋ค์ด์ฃผ์๋๋,
์ญ์ ํ์ ๋ ๋ฐ๋ก ์ด๋ฆ๊น์ง ์ง์์ก๋ค
'TIL > etc.' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[TIL] Chakra UI (4) | 2023.05.23 |
---|---|
[TIL] MongoDB (0) | 2023.05.20 |
[TIL] html2canvas (0) | 2023.05.20 |
[TIL] postman + ๊ณต๊ณต API ๋ถ๋ฌ์ค๊ธฐ (0) | 2023.05.20 |
[TIL] Local Storage (0) | 2023.05.19 |