이미지 갤러리

React 프로젝트 생성

yarn create react-app gallery --template typescript

Main UI 구현

function App() {
  return (
    <div className="App">
      <div className='container'>
        <div className='initial-box'>
          <div className='text-center'>
            이미지가 없습니다.<br/>
            이미지를 추가해주세요.          
          </div>
          <div className='plus-box'>
            +
          </div>
        </div>
      </div>
    </div>
  );
}
.text-center {
  text-align: center;
}

.plus-box {
  width: 100px;
  height: 100px;
  border: solid 1px #707070;
  font-size: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  line-height: 24px;
}

.initial-box {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  gap: 80px;
}

.container {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

이미지 갤러리 구현

function ImageBox(props: {
    src: string
}) {
    return <div className="image-box">
        <img src={props.src} />
    </div>
}

export default ImageBox;
const inpRef = useRef<HTMLInputElement>(null);

    <input type='file' ref={inpRef} />
    <div className='plus-box' onClick={() => {
    inpRef.current?.click()
    }}>
    +
    </div>

Conversion from local image URL to Data URL

    <input type='file' ref={inpRef} onChange={(event) => {
        const file = event.currentTarget.files?.[0];
        if (file) {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onloadend = (event) => {
            setImageList(prev => [...prev, event.target?.result as string]);
            };
        }
    }} />
    {
        imageList.map((path, index) => <ImageBox key={path + index} src={path}/>)
    }
    <div className='plus-box' onClick={() => {
        inpRef.current?.click()
    }}>
    +
    </div>

완성본 보러가기

끝!