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.

>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]);

Leave a Reply