React | Pop Up

짜릿·2021년 4월 6일
0

React

목록 보기
1/1
post-thumbnail

React PopUp Feature

기능 로직

웹사이트 접근 > 팝업 등장 > [로컬스토리지 push > 팝업 지속X > Date 함수 > 일정 시간 지난 후 > 팝업 다시 등장]

기능 구현

  1. 웹사이트 접근

  2. 팝업 등장

  • HAS_VISITED_BEFORE 변수
  • getItem 함수 (로컬스토리지에서 가져오기)
const HAS_VISITED_BEFORE = localStorage.getItem("hasVisitedBefore");
  1. 로컬스토리지 push
  • useEffect
  • useState
  • setItem (로컬스토리지에 넣기)
  • setTimeout (웹사이트 접속 1초 후)
const [popup, setPopup] = useState(false);
useEffect(() => {
    const handleShowModal = () => {
      if (HAS_VISITED_BEFORE && HAS_VISITED_BEFORE > new Date()) {
        return;
      }

      if (!HAS_VISITED_BEFORE) {
        setPopup(true);
        let expires = new Date();
        expires = expires.setHours(expires.getHours() + 3);
        localStorage.setItem("hasVisitedBefore", expires);
      }
    };

    window.setTimeout(handleShowModal, 1000);
  }, [HAS_VISITED_BEFORE]);
  1. 핸들러
  • useState
  const onCanelHandler = () => {
    setPopup(false);
  };

번외

팝업 만들기

  • antd - modal
    <Modal
          visible={popup}
          onCancel={onCanelHandler}
          centered
          footer={null}
          className="popup"
          width="initial"
        >
          <a href="/setting">
            <img src="/images/popup.png" alt="popup" />
          </a>
        </Modal>
profile
야망가, 과정중심주의

0개의 댓글