user15603995
user15603995

Reputation:

How to trigger modal/popup on page first load - React

When user enters the page I would like to have a modal pops up as the first thing with option to choose between USER and AGENT and based on that the content of the page will be updated.

At first, I need to figure out how to trigger the modal on page load and save the chosen option to cookie / localStorage.

I know there is a JavaScript function, something like this:

$(document).ready(function() {
  setTimeout(function() {
    $("#myModal").modal('show');
  }, 2000);

});

The code ^ above will trigger the modal when user is on page for 2 seconds, I would like to achieve the same logic just with react - thinking of useEffect could handle that ?

Also, I am using React Bootstrap, I know that component has some functions e.g onEnter function, but I am not sure if it is usable at all ?

React Modal I am using now that is triggered by button:

const [show, setShow] = useState(false); // trigger

        <Button variant="primary" onClick={() => setShow(true)}>
            Custom Width Modal
        </Button>

Modal itself:

            <Modal
                show={show}
                onHide={() => setShow(false)}
                dialogClassName="modal-90w"
                aria-labelledby="contained-modal-title-vcenter"
            >
                <Modal.Header closeButton>
                    <Modal.Title id="contained-modal-title-vcenter">
                        Lorem Ipsum Dolor
                    </Modal.Title>
                </Modal.Header>
                <Modal.Body>
                    <Row className="text-center justify-content-center">
                        <Col>
                            <Button>USER</Button>
                        </Col>
                        <Col>
                            <Button>AGENT</Button>
                        </Col>
                    </Row>
                </Modal.Body>
            </Modal>

Upvotes: 1

Views: 10040

Answers (2)

Ajith Gopi
Ajith Gopi

Reputation: 1826

Try this

useEffect() with a second argument as an empty list will only be called once, when the component is mounted. You can also check the cookie just before calling setShow.

The below code also adds a delay of 2 seconds.

useEffect(()=>{
  setTimeout(()=>{
    setShow(true)
  }, 2000)
}, [])

Upvotes: 1

Udendu Abasili
Udendu Abasili

Reputation: 1213

Since you say you want the popup to show first you simple need to change this

const [show, setShow] = useState(true)

Upvotes: 2

Related Questions