Besart Marku
Besart Marku

Reputation: 79

How to center Material UI Dialog relative to its parent

I want to position the Material UI Dialog based on the position of its parent. In this case, I want to center it on the second grid item.

 //parent element
 <Grid container>
    <Grid item xs={5} style={{ border: "1px solid black" }}>
      Yerah{" "}
    </Grid>
    <Grid
      item
      xs={7}
      style={{ border: "1px solid black", height: "100vh" }}
    >
      <div style={{ position: "relative" }}>
        //on center of this div i want to position the Dialog
        <SimpleDialog
          selectedValue={selectedValue}
          open={open}
          onClose={handleClose}
        />

        <br />
        <Button
          variant="outlined"
          color="primary"
          onClick={handleClickOpen}
        >
          Open simple dialog
        </Button>
      </div>
    </Grid>
//Dialog component 

const useStyles = makeStyles({
  root: {
    position: "absolute",
    left: "50%",
    top: "50%",
    transform: "translate(-50%, -50%)"
  },
});

 <Dialog
      onClose={handleClose}
      aria-labelledby="simple-dialog-title"
      open={open}
      classes={{
        paper: classes.root
      }}
    >
      <DialogTitle id="simple-dialog-title">Set backup account</DialogTitle>
      <div style={{ padding: 20 }}> Content will go here </div>
    </Dialog>

Here is the sandbox for what I have tried so far but still the position is not being set based on the position of the parent div

https://codesandbox.io/s/material-demo-forked-sugfm?file=/demo.js

enter image description here

Upvotes: 1

Views: 2378

Answers (1)

Ryan Le
Ryan Le

Reputation: 8412

There is a prop in Modal API called container that accept an HTML element.

You could do something like this:

<Dialog
   container={() => document.getElementById('parent-div')}>
</Dialog>

Upvotes: 3

Related Questions