Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Open dialog on load react

I’m trying to open a dialog if the url include a specific string, but it does not work the way I intend. If I just change the dialog state it render too many time (error) and if I useEffect then it works but I cannot close the modal anymore..

export default function Terms() {
  const [open, setOpen] = useState(false);
  const [scroll, setScroll] = useState('paper');

   const handleClickOpen = () => {
    setOpen(true);
    setScroll();
  };

  const handleClose = () => {
    setOpen(false);
  };
  
  //if (/terms-conditions/.test(window.location.href)) {
  //  setOpen(true);
  //} 
  // this gives me Too many render error, same if I call the handleClickOpen()
  
  const descriptionElementRef = useRef(null);

  useEffect(() => {

    // this check if "terms-conditions" appear in the url
    if (/terms-conditions/.test(window.location.href)) {
      setOpen(true);
    } 

    if (open) {
      const { current: descriptionElement } = descriptionElementRef;
      if (descriptionElement !== null) {
        descriptionElement.focus();
      }
    }
  }, [open]);


return(
<Dialog
        open={open}
        onClose={handleClose}
        scroll={scroll}
        aria-labelledby="scroll-dialog-title"
        aria-describedby="scroll-dialog-description"
      >
 <DialogActions>
   <Button onClick={handleClose}>{translate('general.close')}</Button>
 </DialogActions>
</Dialog>
<Button onClick={handleClickOpen}>Terms</Button>
)
}

Thank you.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Split it into two separate useEffect hooks. You are getting infinite loop and you are not able to close the modal because of the unwanted dependency (open) in the first one.

One responsible for checking the URL and opening the modal if the URL fulfills the requirements:

useEffect(() => {
  if (/terms-conditions/.test(window.location.href)) {
    setOpen(true);
  }
}, []); 

Second one responsible for focusing the element.

useEffect(() => {
  if (open) {
    const { current: descriptionElement } = descriptionElementRef;
    if (descriptionElement !== null) {
      descriptionElement.focus();
    }
  }
}, [open]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading