Home > Enterprise >  how to conditionally render dialog Material-ui
how to conditionally render dialog Material-ui

Time:10-20

I am trying to show a dialog box based on the data returned from apollo hook, where I would have to check that one of the values matches an id.

When checker===true I want the dialog to open on render and when the user clicks the Close button, the dialog should close.

 const DialogComponent = () => {
 
    const {data, loading, error} = useQuery(GET_QUERY_DATA)
    const [isDialogOpen, setIsDialogOpen] = useState(false);
    const checker = data && data.getData.some((item_data.id === id))

    const closeDialog = () => {
      setIsDialogOpen(false)
    }
 
    if(checker) {
     setIsDialogOpen(true)
    }

   return( 
        <Dialog
          open={isDialogOpen}
          close={closeDialog}>
                   // dialog content here
            <DialogActions>
              <Button onClick={closeDialog}> Close </Button>
            </DialogActions>
          </Dialog>
   )}

The above errors with too many re-renders.

I have tried a conditional render instead however, seems that the Dialog component never opens even when checker===true (below).

const DialogComponent = () => {
 
    const {data, loading, error} = useQuery(GET_QUERY_DATA)
    const [isDialogOpen, setIsDialogOpen] = useState(false);
    const checker = data && data.getData.some((item_data.id === id))

    const closeDialog = () => {
      setIsDialogOpen(false)
    }
 
    if(checker) {
     setIsDialogOpen(true)
    }

   return( 
        {checker && <Dialog
          open={isDialogOpen}
          close={closeDialog}>
                   // dialog content here
            <DialogActions>
              <Button onClick={closeDialog}> Close </Button>
            </DialogActions>
          </Dialog>
   )}}

I have also tried replacing the open prop value with checker I.e. open={checker} however, then the Dialog box never can be closed even when clicking the Close button.

Any help appreciated.

CodePudding user response:

One problem I see in your code is regarding this part:

if (checker) {
  setIsDialogOpen(true)
}

Every time a state is updated in a component, the component funcion is called again to re-render it with the updated state. So the snippet above is executed again and if checker is true, the state is updated again, then it keeps re-redering again and again.

Try wrapping the snippet above inside a React.useEffet() like this:

React.useEffect(() => {
    setIsDialogOpen(checker)
}, [checker])

CodePudding user response:

The close button does close the dialog, it is being opened again on the next render with

if(checker) {
 setIsDialogOpen(true)
}

you could do:

     <Dialog
      open={isDialogOpen && checker}
      close={closeDialog}>
        <DialogActions>
          <Button onClick={closeDialog}> Close </Button>
        </DialogActions>
      </Dialog>
  • Related