Andhi Irawan
Andhi Irawan

Reputation: 481

How to create a first visit popup in react-bootstrap application

I'm learning to react based on React Bootstrap.

How do I make a first visit popup for my react-bootstrap application?

Here is my code :

import React, {
       Suspense, 
       useState
} from 'react';
import { 
       Modal 
} from "react-bootstrap";

const Popup = props => {
const [show, setShow] = useState(true);
const handleClose = () => setShow(false);

useEffect(() => {
 if (!sessionStorage.popupModal) {
   const timer = setTimeout(() => {
    setIsShown(true);
    sessionStorage.popupModal = 1;
  }, 2000);

  return () => clearTimeout(timer);
 }
}, []);

    return (
        <Modal 
            show={show} 
            onHide={handleClose} 
            centered>
            <Modal.Header closeButton>
                <Modal.Title>
                    Learn React
                </Modal.Title>
            </Modal.Header>
        </Modal>
    );
}

export default Popup;

and here's a screenshot of the results

enter image description here

I tried to follow this tutorial using componentDidMount but don't know how to apply it: first visit popup in react application

I ended up using useEffect from How to create a popup modal in React but it didn't work either

Upvotes: 1

Views: 897

Answers (1)

Bruno Monteiro
Bruno Monteiro

Reputation: 4519

You should probably use localStorage instead of sessionStorage since localStorage will persist even if the user closes the browser.

Your code looks good, you only missed the syntax to read and save your variable from the storage (which has nothing to do with React, just Javascript itself).

Your useEffect should look like this:

useEffect(() => {
  const popupModalValue = localStorage.getItem("popupModal")
  if (!popupModalValue) {
    const timer = setTimeout(() => {
      setIsShown(true);
      localStorage.setItem("popupModal", "1");
    }, 2000);

    return () => clearTimeout(timer);
  }
}, []);

PS: localStorage will only accept strings as its value. More info here: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Upvotes: 1

Related Questions