Search code examples
javascriptreactjsbootstrap-modal

ReactJS show modal after delay


I'm trying to show a Bootstrap modal after delay, however only home page is shown. Please see my code below (no error is detected).

App.js:

import { useEffect, useState } from "react";
import Home from "./pages/Home";
import Modal from 'react-bootstrap/Modal';

function MyVerticallyCenteredModal() {
    return (
      <Modal
        size="lg"
        aria-labelledby="contained-modal-title-vcenter"
        centered
      >
        <Modal.Header closeButton>
          <Modal.Title id="contained-modal-title-vcenter">
            Modal heading
          </Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <h4>Centered Modal</h4>
          <p>
            Some Text
          </p>
        </Modal.Body>
      </Modal>
    );
}

function App() {

    const [modalShow, setModalShow] = useState(false);

    useEffect(() => {
        const timeId = setTimeout(() => setModalShow(true), 3000)
    
        return () => clearTimeout(timeId)
    })

    return (
        <div className="App">
            <Home />
            {modalShow && (<MyVerticallyCenteredModal />)}
        </div>
    );
}

export default App;

Do you have any idea what's wrong? Thank you.


Solution

  • I don't think the timeout logic is the problem here, because even if the conditional modalShow is removed, the component still doesn't render.

    Try <Modal.Dialog> instead of just <Modal> for the bootstrap component

    https://react-bootstrap.github.io/components/modal/