Center Popover in Viewport

Viewed 3271

How should I center a React Material-UI Popover in the viewport?

My app is built on the Next.js framework, which is built on React. (I have included the full dependencies from my package.json below.)

I have an element that opens a Popover when it is clicked:

        <Popover
            id="video-popover"
            open={Boolean(video)}
            onClose={this.handleClose}
            anchorOrigin={{
                vertical: 'center',
                horizontal: 'center'
            }}
            transformOrigin={{
                vertical: 'center',
                horizontal: 'center'
            }}
        >
            <video controls autoPlay src={`/static/${video}`}>
                Your browser does not support the
                    <code>video</code> element.
                </video>
        </Popover>

I would like to get the video to be centered in the view.

Normally I would set the anchorEl property of the Popover element and the Popover would be centered over that anchor element. But, what element should I use to center in the viewport?


In case it's not obvious, the onClick handler just sets state.video to the filename of the video to be played. The onClose handler sets state.video to null. If you need me to upload more of the JSX code, let me know, but I'm pretty sure it's not relevant to the centering of the Popover on the viewport.

Here are my dependencies:

  "dependencies": {
    "@material-ui/core": "^3.6.2",
    "next": "^7.0.2",
    "react": "^16.6.3",
    "react-dom": "^16.6.3",
    "react-icons": "^3.2.2"
  },
2 Answers

There is an other way to do it:

Popove has already a Div element with fixed position which contains the popover content, so we can just give it the style, and set the anchorReference to none.

import React from 'react';
import {
  makeStyles,
  Popover,
} from '@material-ui/core';

const useStyles = makeStyles (theme => ({
  popoverRoot: {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
  },
}));

const CenteredPopOver = ({open}) => {
  const classes = useStyles();

  return (
    <Popover
      open
      anchorReference={"none"}
      classes={{
        root: classes.popoverRoot,
       }}
    >
      // what ever should be in the popover
      <div>I am in the center</div>
    </Popover>
  )
}

You could make a full screen popover layer behind it, like modal's usually have. Make a div that's fixed position with a width of 100vw and a height of 100vh. Then use that as your anchor element. You'll have to hide and show it as needed.

Related