n일 동안 보지 않기 팝업 구현

togongs·2022년 10월 28일
0

2022

목록 보기
6/19

index.tsx

import Modal from '../components/Modal';
import { useState } from 'react';

const Home: NextPage = () => {
  const [openModal, setOpenModal] = useState<boolean>(true);
  const [hasCookie, setHasCookie] = useState<boolean>(true);
  
  const getExpiredPopUpDate = (days: number) => {
    const date = new Date();
    date.setDate(date.getDate() + days); // 일
    return date;
  };

  const closeModalUntilExpires = () => {
    // if (!appCookies) return;
    const expires = getExpiredPopUpDate(1); // 1일
    setCookie('MODAL_EXPIRES', true, { path: '/', expires });
    setOpenModal(false);
  };

  useEffect(() => {
    if (getCookie('MODAL_EXPIRES')) return;
    console.log(getCookie('MODAL_EXPIRES'));
    setHasCookie(false);
  }, []);

  return (
    <>
      <Header />
      <Container>
        <div>
          {openModal && !hasCookie && (
          <PopUp
            closeModal={() => setOpenModal(false)}
            closeModalUntilExpires={closeModalUntilExpires}
          />
        )}
        </div>
      <Footer />
      </Container>
    </>
  );
};

export default Home;

Modal.tsx

import React from 'react';
import styled from 'styled-components';

const Container = styled.div`
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
`;

const ModalBackground = styled.div`
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.75);
  z-index: 1000;
`;

const ModalContainer = styled.div`
  z-index: 1001;
`;

const ModalContent = styled.div`
  width: 350px;
  height: 500px;
  background-color: gainsboro;
  padding: 25px;
`;

const ModalCloseWrapper = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: white;
  padding: 5px 25px;

  p {
    cursor: pointer;
  }
`;

interface IModalProps {
  closeModal: () => void;
}

function PopUp({ closeModal, closeModalUntilExpires }: IModalProps) {
  return (
    <Container>
      <ModalBackground />
      <ModalContainer>
        <ModalContent>
          Lorem ipsum 
        </ModalContent>
        <ModalCloseWrapper>
          <p onClick={closeModalUntilExpires}>오늘 하루 더 이상 보지 않기</p>
          <p onClick={closeModal}>닫기</p>
        </ModalCloseWrapper>
      </ModalContainer>
    </Container>
  );
}

export default PopUp;
  • 마운트 되자마자 PopUp이 떴으면 하므로, openModal의 초기값을 true로 설정
  • PopUp의 닫기를 클릭하면 해당 모달이 꺼지도록 setOpenModal(false) 함수prop으로 보내준다

참고 - Reference

profile
개발기록

0개의 댓글