How to create a Popover in Material-UI React
Material-UI Popover:
Popover component is used to show a message or some other content on top of another component. This post will show you how to create a Popover with exmaples.
YouTube video:
I have published one video on Popover on YouTube. You can check it here:
Example of Popover:
Let's take a look at the below example:
import { Button, Popover, Typography } from "@material-ui/core";import { useState } from "react";function App() {const [anchor, setAnchor] = useState(null);const openPopover = (event) => {setAnchor(event.currentTarget);};return (<div><Button style={{ margin: 100 }} variant="contained" onClick={openPopover}>Click me</Button><Popover open={Boolean(anchor)} anchorEl={anchor}><Typography variant="h6">Hello World</Typography></Popover></div>);}export default App;
It will show one Popover if we click on the button. The open props is used to define if the Popover is visible or not. On clicking the button, we are setting the anchor value, which is provided as the anchorEl to the Popover.
If you run it and click on the button, it will show one Popover over the button:
anchorOrigin and transformOrigin:
We can adjust the position of the Popover by using anchorOrigin and transformOrigin props. Both takes one object with vertical and horizontal keys.
anchorOrigin defines the position with respect to the view whose anchor we are using. transformOrigin defines the position for the Popover.
For example:
<div><Button style={{ margin: 300 }} variant="contained" onClick={openPopover}>Click me</Button><Popoveropen={Boolean(anchor)}anchorEl={anchor}anchorOrigin={{vertical: "top",horizontal: "left",}}transformOrigin={{vertical: "bottom",horizontal: "right",}}><Typography variant="h6">Hello World</Typography></Popover></div>
It will give the below output:
The bottom of Popover is aligned with the top of the button. Also, right of Popover is aligned with the left of the button. Each can have top, bottom, left and right.
Complete example:
import { Button, Popover, Typography } from "@material-ui/core";import { useState } from "react";function App() {const [anchor, setAnchor] = useState(null);const openPopover = (event) => {setAnchor(event.currentTarget);};return (<div><Button style={{ margin: 300 }} variant="contained" onClick={openPopover}>Click me</Button><Popoveropen={Boolean(anchor)}anchorEl={anchor}anchorOrigin={{vertical: "top",horizontal: "left",}}transformOrigin={{vertical: "bottom",horizontal: "right",}}><Typography variant="h6">Hello World</Typography></Popover></div>);}export default App;