TIL39-02 리액트 모달창 구현

김태혁·2023년 2월 22일
0

TIL

목록 보기
120/205

모달창 구현하기

1. 기본적인 모달창

function Modal(){
  const [showModal, setShowModal] = useState(false);

  return (
    <>
      <button onClick={() => setShowModal(true)}>Open Modal</button>
      {showModal && (
        <Modal>
          <ModalContent>
            <CloseButton onClick={() => setShowModal(false)}>&times;</CloseButton>{/*&times=> 곱하기 표시인 x를 의미한다.*/}
            <h2>Modal Title</h2>
            <p>Modal content goes here</p>
          </ModalContent>
        </Modal>
      )}
    </>
  );
}
export default Modal;

styled-components를 통한 모달창 효과 주기

import styled from 'styled-components';

const CloseButton = styled.button`
  position: absolute;
  top: 10px;
  right: 10px;
  font-size: 1.5rem;
  border: none;
  background-color: transparent;
  cursor: pointer;
`;

const Modal = styled.div`
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5);
`;

const ModalContent = styled.div`
  position: relative;
  width: 50%;
  height: 50%;
  background-color: white;
  padding: 20px;
`;

3. 모달창 바깥을 클릭했을 때 꺼지게 하기

  • useRef를 활용해 Dom요소에 접근한다.
  • Dom요소를 활용하여 클릭시의 이벤트 값을 얻고, 그 값을 이용해 클릭의 구역을 결정한다.
  • if문 안의 코드가 위와 같은 구조이다.
 const handleClickOutsideModal = (event) => {
    if (modalRef.current && !modalRef.current.contains(event.target)) {
      setShowModal(false);
    }
  };
 return (
    <>
      <button setShowModal(true)}>Open Modal</button>
      {showModal && (
        <Modal onClick={handleClickOutsideModal}>
          <ModalContent ref={modalRef}>
            <CloseButton onClick={() => setShowModal(false)}>&times;</CloseButton>
            <p>모달 내용</p>
          </ModalContent>
       </Modal>
      )}
    </>
  );
}

export default Modal;
profile
도전을 즐기는 자

0개의 댓글