Search code examples
reactjspopup

its my modal How to show modal popup after time delay using react hooks


its my modal How to show modal popup after time delay using react hooks its like a ad in my pagee it should be shown after some time of initizal page load

  const [open, setOpen] = React.useState(false);
  const handleOpen = () => setOpen(true);
  const handleClose = () => setOpen(false);
  return (
    <div>
      <Button onClick={handleOpen}>Open modal</Button>
      <Modal
        open={open}
        onClose={handleClose}
        aria-labelledby="modal-modal-title"
        aria-describedby="modal-modal-description"
      >
        <Box sx={style}>
          <Typography id="modal-modal-title" variant="h6" component="h2">
            Text in a modal
          </Typography>
          <Typography id="modal-modal-description" sx={{ mt: 2 }}>
            Duis mollis, est non commodo luctus, nisi erat porttitor ligula.
          </Typography>
        </Box>
      </Modal>
    </div>
  );
}

Solution

  • what you can do is modify your handleOpen function in this way:

    const handleOpen = () => {
       const timer =  setTimeout(() => {
            setOpen(true);
        }, 1000)
         return () => clearTimeout(timer);
    }
    

    and if you want to automatically open your modal/Add you can use useEffect this way:

    useEffect(() => {
        handleOpen();
    }, [])