토이프로젝트 - 프로필 페이지 만들기

프로필 페이지 만들기 (8) - 모달 UI 구현

vitamin3000 2025. 2. 12. 18:24

 

이번 포스트에서는 구현한 모달 UI에 대한 내용을 작성해보고자 한다.

 

모달에서 가장 중요한 부분은 출력되는 모달 컴포넌트를 제외한 나머지 부분을 접근이 불가능한 상태로 보여지게하는 것이다.

 

이를 위해서는, 배경색을 회색으로 설정하는 것이다.

  Overlay: styled.div`
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.7);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1;
  `,

 

또 하나 중요한 부분은 z-index를 사용하여 다른 컴포넌트 위에 위치하게 하였다.

 

 

구현한 모달

 

위의 모달 이미지를 보면, 한 화면에 하나의 아이템 값만 출력하고 왼쪽 또는 오른쪽으로 index를 이동하게 하는데, 이를 컨트롤하는 코드는 다음과 같다.

 

  const [currentIndex, setCurrentIndex] = useState(initialIndex);
  const currentItem: ModalItem = modalItems[currentIndex];
  
  const handleLeftClick = () => {
    setCurrentIndex(
      currentIndex > 0 ? currentIndex - 1 : modalItems.length - 1
    );
  };

  const handleRightClick = () => {
    setCurrentIndex(
      currentIndex < modalItems.length - 1 ? currentIndex + 1 : 0
    );
  };

 

currentIndex가 변경될 때마다 리랜더링 될 것이다.

 

추가적으로 .. +

esc를 키보드로 누르거나 출력된 모달창이 아닌 다른 곳을 클릭하면 모달창이 닫히도록 할 수 있다.

  const handleKeyDown = (event: KeyboardEvent) => {
    if (event.key === 'Escape') onClose();
  };

  if (isOpen) {
    window.addEventListener('keydown', handleKeyDown);
  } else {
    window.removeEventListener('keydown', handleKeyDown);
  }

 

 

 

아이콘은 react-icons를 사용하였다