skip to Main Content
<div className="Image popup">
  <Modal
    isOpen={modalIsOpen}
    onRequestClose={closeModal}
    contentLabel="Image popup"
  >
    <img src="../img/navratri-1.png" alt="Image popup" />
    <button onClick={closeModal}>Close</button>
  </Modal>
</div>;

useEffect(() => {
  const hasShownImagePopup = localStorage.getItem("hasShownImagePopup");
  if (!hasShownImagePopup) {
    localStorage.setItem("hasShownImagePopup", "true");
    setModalIsOpen(true);
  }
}, []);

const closeModal = () => {
  setModalIsOpen(false);
};

In this, I am expecting a popup image to show on screen. Like a website where, when the user enters the home page, the image is shown, and when the user clicks the close button, the image is closed.

2

Answers


  1. if (!hasShownImagePopup) {
    

    Here, !hasShownImagePopup only returns true when hasShownImagePopup is "".

    Because in Local Storage, data is stored in a string format.

    So, we should check if hasShownImagePopup is not "true".

    if (hasShownImagePopup !== "true") {
    

    Also, you should probably set hasShownImagePopup in LocalStorage to "false" when you close the Modal. This will make the popup showup again when you visit the page again.

    const closeModal = () => {
      localStorage.setItem("hasShownImagePopup", "false");
      setModalIsOpen(false);
    };
    

    Here is a CodePen example.

    Login or Signup to reply.
  2. Can you try the below code snippet,

    import React, { useState, useEffect } from 'react';
    import Modal from 'react-modal';
    
    const ImagePopup = () => {
      const [modalIsOpen, setModalIsOpen] = useState(false);
    
      useEffect(() => {
        const hasShownImagePopup = localStorage.getItem('hasShownImagePopup');
    
        if (!hasShownImagePopup) {
          localStorage.setItem('hasShownImagePopup', 'true');
          setModalIsOpen(true);
        }
      }, []);
    
      const closeModal = () => {
        setModalIsOpen(false);
      };
    
      return (
        <div className="Image popup">
          <Modal
            isOpen={modalIsOpen}
            onRequestClose={closeModal}
            contentLabel="Image popup"
          >
            <img src={require('../img/navratri-1.png')} alt="Image popup" />
            <button onClick={closeModal}>Close</button>
          </Modal>
        </div>
      );
    };
    
    export default ImagePopup;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search