MUI Popover not anchoring properly (AnchorEl, React, material-table, MUI) - reactjs

I've looked through many questions regarding popover anchoring, but I haven't seen any when using a MaterialTable element from the material-table library: https://github.com/mbrn/material-table .
While debugging it looks like the anchorEl properly holds the button reference, but it seems to rerender a second time and loses the reference. From what I can tell this is from the button being remounted. So the final rendering puts the popover in the top left corner of the screen by default. I'm wondering if anyone has found a way to either prevent this remount or some other workaround.
export class UsersList extends Component {
constructor(props) {
super(props);
this.state = {
anchorEl: null,
anchorReference: "anchorEl"
};
}
render() {
const { classes } = this.props;
var { anchorEl } = this.state;
const open = Boolean(anchorEl);
return (
<MaterialTable
isLoading={this.state.isLoading}
columns={[
{ title: "Username", field: "username" },
...more columns
]}
data={this.state.users}
onRowClick={(evt, selectedRow) => this.setState({ selectedRow })}
//where I update my anchorEl on a click on the "edit" icon
actions={[
{
icon: "edit",
tooltip: "Edit",
onClick: (event, rowData) => {
this.setState({ anchorEl: event.currentTarget });
}
},
},
]}
components={{
Body: props => (
<React.Fragment>
<MTableBody {...props} />
<Popover
//a breakpoint here is hit twice. First time with valid ref, second time without ref
getContentAnchorEl={null}
id="myId"
open={open}
onClose={this.handlePopoverClose.bind(this)}
anchorEl={anchorEl}
getContentAnchorEl={null}
anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
transformOrigin={{ vertical: "top", horizontal: "center" }}
open={open}
>
<Typography>The content of the Popover.</Typography>
</Popover>
EDIT** codesandbox running example: If you click on the edit column row item a popup shows up in the top left hand of the screen instead of next to the rowitem: https://codesandbox.io/s/loving-tdd-8r910?file=/src/App.js

Move popover to a separate component so that anchorEl would be in the same component as Popover. Example with menu:
function MenuCell() {
const [anchorEl, setAnchorEl] = useState(null);
return (
<div>
<IconButton
aria-label="more"
aria-haspopup="true"
onClick={(event) => setAnchorEl(event.currentTarget)}
>
<MoreVertIcon />
</IconButton>
<Menu
anchorEl={anchorEl}
keepMounted
open={Boolean(anchorEl)}
onClose={() => setAnchorEl(null)}
>
<MenuItem selected={false} onClick={() => setAnchorEl(null)}>
Item 1
</MenuItem>
<MenuItem selected={false} onClick={() => setAnchorEl(null)}>
Item 2
</MenuItem>
<MenuItem selected={false} onClick={() => setAnchorEl(null)}>
Item 3
</MenuItem>
</Menu>
</div>
)
}
And use in Column cell definition:
function CustomTable() {
const menuColumn = {
id: 'menus',
Header: '',
Cell: ({ row }) => <MenuCell row={row} />,
};
// ...
}

Related

React component doesn't render on MUI MenuItem onClick event

I have a simple mui Menu, where one MenuItem should render another React component. The problem is that my Menu is rendered in another file, where close and handleClick functions are defined.
Problem: The component doesn't render on the MenuItem click. Seems like it is because setAnchor(null); in the App component sets the anchor to null always. Does this mean I need to use a different anchor? If yes, how?
The Menu component code is as follows:
interface Props {
handler: Handler;
anchor: HTMLButtonElement | null;
onClose: () => void;
}
const AddDataMenu = ({ handler,anchor, onClose }: Props) => {
const renderDataPopOver = () => {
console.log('this is clicked'); <<<<<<<<<< I can see this function is accessed
<AddDataPopover handler={handler} anchor={anchor} onClose={onClose} />;
};
return (
<div>
<Menu
anchorEl={anchor}
open={Boolean(anchor)}
onClose={onClose}
sx={{ width: 320, maxWidth: '100%' }}
>
<MenuItem onClick={renderDataPopOver}>
<ListItemIcon>
<DataIcon />
</ListItemIcon>
<Typography>item 1</Typography>
</MenuItem>
</Menu>
</div>
);
};
export default AddDataMenu;
This is the Main Component where my Menu is rendered.
const App = ({ scope }) => {
const ref = useRef<HTMLButtonElement>(null);
const [anchor, setAnchor] = useState<HTMLButtonElement | null>(null);
const [handler, setHandler] = useState<Handler>();
const close = () => { <<<<<<< this is accessed before MenuItem click
setAnchor(null);
};
const handleClick = () => { <<<<<<< this is accessed before MenuItem click
setAnchor(ref.current);
};
return showAdd && handler ? (
<MessageContainer
message={'test'}
actions={
<Box ml={1}>
<Button ref={ref} color="primary" variant="contained" onClick={handleClick}>
{t('Visualization.chart-initial-states.AddColumns')}
</Button>
<AddDataMenu handler={handler} anchor={anchor} onClose={close} />
</Box>
}
/>
) : (
<DisplayError />
);
};
export default App;
Assuming that the goal is to render a secondary Popover beside Menu on click of MenuItem, perhaps indeed the component would need to assign any MenuItem that triggers it as anchorEl to the rendered Popover.
Basic live example on: stackblitz (this and below examples omitted everything except for the Menu from the original posted code for simplicity).
In AddDataMenu, add AddDataPopover to the output with its initial anchorEl as null so it would not render immediately. Matching anchorEl can be assigned in the event of handleOpen.
A ref array is used to reference multiple MenuItem here, but this is an optional approach.
const AddDataMenu = ({ anchor, onClose }) => {
const [itemAnchor, setItemAnchor] = useState(null);
const itemRef = useRef([]);
const handleClose = () => {
setItemAnchor(null);
};
const handleOpen = (index) => {
setItemAnchor(itemRef.current[index]);
};
return (
<>
<Menu
anchorEl={anchor}
open={Boolean(anchor)}
onClose={onClose}
sx={{
width: 320,
maxWidth: '100%',
}}
>
{[1, 2, 3].map((item, index) => (
<MenuItem
ref={(node) => (itemRef.current[index] = node)}
key={index}
onClick={() => handleOpen(index)}
sx={{ p: 2 }}
>
<ListItemIcon>
<DataIcon />
</ListItemIcon>
<Typography>{`item ${item}`}</Typography>
</MenuItem>
))}
</Menu>
<AddDataPopover anchor={itemAnchor} onClose={handleClose} />
</>
);
};
In AddDataPopover, wire up the anchorEl to the Popover and style the component to be rendered beside active MenuItem.
const AddDataPopover = ({ anchor, onClose }) => {
return (
<Popover
id={'my-popover'}
open={Boolean(anchor)}
anchorEl={anchor}
onClose={onClose}
anchorOrigin={{
vertical: 'center',
horizontal: 'right',
}}
transformOrigin={{
vertical: 'center',
horizontal: 'left',
}}
>
<Typography sx={{ p: 2 }}>The content of Data Popover.</Typography>
</Popover>
);
};

React MUI popover contains wrong data

I have an array of data and map it into Popover component. These components have MenuItem which contains some data. But they render only the last data, instead of the different data that exists. Example:
Wrong data, should be to 59 as shown below. The textfield and popover contain the same MenuItem components, only thing different is the popovers.
Code:
const [anchorEl, setAnchorEl] = React.useState(null);
const handlePopoverClick = (event) => {
setAnchorEl(event.currentTarget);
};
const handlePopoverClose = () => {
setAnchorEl(null);
};
const open = Boolean(anchorEl);
const id = open ? "simple-popover" : undefined;
// New section
<Fab
className={classes.fabStyle}
size="small"
variant="outlined"
onClick={handlePopoverClick}
>
<ExpandMoreIcon />
</Fab>
<Popover
id={id}
open={open}
className={classes.popoverContainer}
anchorEl={anchorEl}
onClose={handlePopoverClose}
anchorOrigin={{
vertical: "bottom",
horizontal: "center",
}}
PaperProps={{ elevation: 1 }}
>
{action.children.map((child) => {
if (child.type === "link") {
console.log(child.to);
return (
<MenuItem>
<Link
style={{
textDecoration: "none",
color:
themes.default.palette
.text.primary,
}}
to={child.to}
>
{child.label}
{child.to}
</Link>
</MenuItem>
);
} else if (
child.type === "dialog"
) {
return (
<MenuItem
onClick={() =>
child.handleOpenDialog(row)
}
>
{child.label}
</MenuItem>
);
}
})}
</Popover>

React Display Separate Popover Component on Menu Click

I have the below menu:
So, ideally you'd click on those 3 dots which would open up another box next to it, I decided to use a popover(https://material-ui.com/components/popover/).. The problem is that when you click the 3 dots nothing happens. I assume this is because onClick function returns a functional popover component but that doesn't get displayed. I put in debuggers and alerts inside the functional component no hit at all.
This is those 3 dots
<IconButton
aria-describedby="simple-popover"
variant="contained"
onClick={e => this.moreClick(e, props.children)}
>
<More />
</IconButton>
This is moreClick function
moreClick = (e, officeAccount) => {
return (
<AccountFavoritesPopover element={e} officeAccount={officeAccount} />
);
};
This is the whole popover
import React from "react";
import Popover from "#material-ui/core/Popover";
export default function AccountFavoritesPopover(element, officeAccount) {
const anchorEl = element;
const open = Boolean(anchorEl);
const id = open ? "simple-popover" : undefined;
return (
<div>
<Popover
id={id}
open={open}
anchorEl={anchorEl}
//onClose={alert}
anchorOrigin={{
vertical: "top",
horizontal: "right"
}}
transformOrigin={{
vertical: "top",
horizontal: "left"
}}
>
<div>{officeAccount}</div>
</Popover>
</div>
);
}
Does popover have to be inside the main file? Currently the 3 dots is in the main file and AccountFavoritesPopover is a whole separate file.
I attempted to put "AccountFavoritesPopover" code inside the main file but I cannot utilize useState in the main file because it's a class. Also, I cannot convert it to actual state and use setState because once setState kicks in, the menu will disappear...
Edit:
Below is the Menu
<Creatable
id="Select"
menuIsOpen={this.state.Focused}
components={{
Option: this.Option
}}
/>
Below is the Options inside menu
<div style={{ position: "relative" }}>
<components.Option {...props} />
<div id="MoreBox">
<IconButton
aria-describedby="simple-popover"
variant="contained"
onClick={e => this.moreClick(e, props.children)}
>
<More />
</IconButton>
</div>
</div>
Try this, this should work(Not tested)
Main.js
export default class Main extends Component {
constructor(props) {
this.state = {
selectedIndex: 0,
selectedId: 0,
anchorEl: null
};
}
moreClick = (anchorEl, selectedId, selectedIndex) => {
this.setState({
selectedId,
selectedIndex,
anchorEl,
open: true,
});
}
handleClose = () => {
this.setState({
open: false
});
}
render() {
const menu = [
{
id: 1,
text: '002',
more: 'more 003'
},
{
id: 2,
text: '003',
more: 'more 003'
},
{
id: 3,
text: '004',
more: 'more 003'
}
]
const menuDom = menu.map((m, index) => {
return (
<IconButton
key={m.id}
aria-describedby="simple-popover"
variant="contained"
onClick={e => this.moreClick(e.currentTarget, index, m.id)}>
{m.text}
</IconButton>
)
})
const more = (<More>{menu[this.state.selectedIndex].text}</More>)
return (
<div>
{menuDom}
<AccountFavoritesPopover open={this.state.open} anchorEl={this.state.anchorEl} onClose={this.handleClose}>
{more}
</AccountFavoritesPopover>
</div>
)
}
}
AccountFavoritesPopover.js
export default function AccountFavoritesPopover(open, anchorEl, onClose) {
const id = open ? "simple-popover" : undefined;
return (
<div>
<Popover
id={id}
open={open}
anchorEl={anchorEl}
onClose={onClose}
anchorOrigin={{
vertical: "top",
horizontal: "right"
}}
transformOrigin={{
vertical: "top",
horizontal: "left"
}}
>
<div>{this.props.children}</div>
</Popover>
</div>
);
}

How to Make Material-UI Menu based on Hover, not Click

I am using Material-UI Menu.
It should work as it was, but just using mouse hover, not click.
Here is my code link: https://codesandbox.io/embed/vn3p5j40m0
Below is the code of what I tried. It opens correctly, but doesn't close when the mouse moves away.
import React from "react";
import Button from "#material-ui/core/Button";
import Menu from "#material-ui/core/Menu";
import MenuItem from "#material-ui/core/MenuItem";
function SimpleMenu() {
const [anchorEl, setAnchorEl] = React.useState(null);
function handleClick(event) {
setAnchorEl(event.currentTarget);
}
function handleClose() {
setAnchorEl(null);
}
return (
<div>
<Button
aria-owns={anchorEl ? "simple-menu" : undefined}
aria-haspopup="true"
onClick={handleClick}
onMouseEnter={handleClick}
>
Open Menu
</Button>
<Menu
id="simple-menu"
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={handleClose}
onMouseLeave={handleClose}
>
<MenuItem onClick={handleClose}>Profile</MenuItem>
<MenuItem onClick={handleClose}>My account</MenuItem>
<MenuItem onClick={handleClose}>Logout</MenuItem>
</Menu>
</div>
);
}
export default SimpleMenu;
The code below seems to work reasonably. The main changes compared to your sandbox are to use onMouseOver={handleClick} instead of onMouseEnter on the button. Without this change, it doesn't open reliably if the mouse isn't over where part of the menu will be. The other change is to use MenuListProps={{ onMouseLeave: handleClose }}. Using onMouseLeave directly on Menu doesn't work because the Menu includes an overlay as part of the Menu leveraging Modal and the mouse never "leaves" the overlay. MenuList is the portion of Menu that displays the menu items.
import React from "react";
import Button from "#material-ui/core/Button";
import Menu from "#material-ui/core/Menu";
import MenuItem from "#material-ui/core/MenuItem";
function SimpleMenu() {
const [anchorEl, setAnchorEl] = React.useState(null);
function handleClick(event) {
if (anchorEl !== event.currentTarget) {
setAnchorEl(event.currentTarget);
}
}
function handleClose() {
setAnchorEl(null);
}
return (
<div>
<Button
aria-owns={anchorEl ? "simple-menu" : undefined}
aria-haspopup="true"
onClick={handleClick}
onMouseOver={handleClick}
>
Open Menu
</Button>
<Menu
id="simple-menu"
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={handleClose}
MenuListProps={{ onMouseLeave: handleClose }}
>
<MenuItem onClick={handleClose}>Profile</MenuItem>
<MenuItem onClick={handleClose}>My account</MenuItem>
<MenuItem onClick={handleClose}>Logout</MenuItem>
</Menu>
</div>
);
}
export default SimpleMenu;
I've updated Ryan's original answer to fix the issue where it doesn't close when you move the mouse off the element to the side.
How it works is to disable the pointerEvents on the MUI backdrop so you can continue to detect the hover behind it (and re-enables it again inside the menu container). This means we can add a leave event listener to the button as well.
It then keeps track of if you've hovered over either the button or menu using currentlyHovering.
When you hover over the button it shows the menu, then when you leave it starts a 50ms timeout to close it, but if we hover over the button or menu again in that time it will reset currentlyHovering and keep it open.
I've also added these lines so the menu opens below the button:
getContentAnchorEl={null}
anchorOrigin={{ horizontal: "left", vertical: "bottom" }}
import React from "react";
import Button from "#material-ui/core/Button";
import Menu from "#material-ui/core/Menu";
import MenuItem from "#material-ui/core/MenuItem";
import makeStyles from "#material-ui/styles/makeStyles";
const useStyles = makeStyles({
popOverRoot: {
pointerEvents: "none"
}
});
function SimpleMenu() {
let currentlyHovering = false;
const styles = useStyles();
const [anchorEl, setAnchorEl] = React.useState(null);
function handleClick(event) {
if (anchorEl !== event.currentTarget) {
setAnchorEl(event.currentTarget);
}
}
function handleHover() {
currentlyHovering = true;
}
function handleClose() {
setAnchorEl(null);
}
function handleCloseHover() {
currentlyHovering = false;
setTimeout(() => {
if (!currentlyHovering) {
handleClose();
}
}, 50);
}
return (
<div>
<Button
aria-owns={anchorEl ? "simple-menu" : undefined}
aria-haspopup="true"
onClick={handleClick}
onMouseOver={handleClick}
onMouseLeave={handleCloseHover}
>
Open Menu
</Button>
<Menu
id="simple-menu"
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={handleClose}
MenuListProps={{
onMouseEnter: handleHover,
onMouseLeave: handleCloseHover,
style: { pointerEvents: "auto" }
}}
getContentAnchorEl={null}
anchorOrigin={{ horizontal: "left", vertical: "bottom" }}
PopoverClasses={{
root: styles.popOverRoot
}}
>
<MenuItem onClick={handleClose}>Profile</MenuItem>
<MenuItem onClick={handleClose}>My account</MenuItem>
<MenuItem onClick={handleClose}>Logout</MenuItem>
</Menu>
</div>
);
}
export default SimpleMenu;
Using an interactive HTML tooltip with menu items works perfectly, without requiring you to necessarily click to view menu items.
Here is an example for material UI v.4.
import React from 'react';
import { withStyles, Theme, makeStyles } from '#material-ui/core/styles';
import Tooltip from '#material-ui/core/Tooltip';
import { MenuItem, IconButton } from '#material-ui/core';
import MoreVertIcon from '#material-ui/icons/MoreVert';
import styles from 'assets/jss/material-dashboard-pro-react/components/tasksStyle.js';
// #ts-ignore
const useStyles = makeStyles(styles);
const LightTooltip = withStyles((theme: Theme) => ({
tooltip: {
backgroundColor: theme.palette.common.white,
color: 'rgba(0, 0, 0, 0.87)',
boxShadow: theme.shadows[1],
fontSize: 11,
padding: 0,
margin: 4,
},
}))(Tooltip);
interface IProps {
menus: {
action: () => void;
name: string;
}[];
}
const HoverDropdown: React.FC<IProps> = ({ menus }) => {
const classes = useStyles();
const [showTooltip, setShowTooltip] = useState(false);
return (
<div>
<LightTooltip
interactive
open={showTooltip}
onOpen={() => setShowTooltip(true)}
onClose={() => setShowTooltip(false)}
title={
<React.Fragment>
{menus.map((item) => {
return <MenuItem onClick={item.action}>{item.name}</MenuItem>;
})}
</React.Fragment>
}
>
<IconButton
aria-label='more'
aria-controls='long-menu'
aria-haspopup='true'
className={classes.tableActionButton}
>
<MoreVertIcon />
</IconButton>
</LightTooltip>
</div>
);
};
export default HoverDropdown;
Usage:
<HoverDropdown
menus={[
{
name: 'Item 1',
action: () => {
history.push(
codeGeneratorRoutes.getEditLink(row.values['node._id'])
);
},
},{
name: 'Item 2',
action: () => {
history.push(
codeGeneratorRoutes.getEditLink(row.values['node._id'])
);
},
},{
name: 'Item 3',
action: () => {
history.push(
codeGeneratorRoutes.getEditLink(row.values['node._id'])
);
},
},{
name: 'Item 4',
action: () => {
history.push(
codeGeneratorRoutes.getEditLink(row.values['node._id'])
);
},
},
]}
/>
I gave up using Menu component because it implemented Popover. To solve the overlay problem I had to write too much code. So I tried to use the old CSS way:
CSS: relative parent element + absolute menu element
Component: Paper + MenuList
<ListItem>
<Link href="#" >
{user.name}
</Link>
<AccountPopover elevation={4}>
<MenuList>
<MenuItem>Profile</MenuItem>
<MenuItem>Logout</MenuItem>
</MenuList>
</AccountPopover>
</ListItem>
styled components:
export const ListItem = styled(Stack)(() => ({
position: 'relative',
"&:hover .MuiPaper-root": {
display: 'block'
}
}))
export const AccountPopover = styled(Paper)(() => ({
position: 'absolute',
zIndex:2,
right: 0,
top: 30,
width: 170,
display: 'none'
}))
use **MenuListProps** in the Menu component and use your menu **closeFunction** -
MenuListProps={{ onMouseLeave: handleClose }}
example-
<Menu
dense
id="demo-positioned-menu"
anchorEl={anchorEl}
open={open}
onClose={handleCloseMain}
title={item?.title}
anchorOrigin={{
vertical: "bottom",
horizontal: "right",
}}
transformOrigin={{
vertical: "top",
horizontal: "center",
}}
MenuListProps={{ onMouseLeave: handleClose }}
/>
I hope it will work perfectly.

How do I style the Material-UI Menu Popover with JSS?

I have a Code Sandbox here: https://codesandbox.io/s/0qv1jwlmlv
What I'm doing is pretty straight forward:
class SimpleMenu extends React.Component {
state = {
anchorEl: null
};
handleClick = event => {
this.setState({ anchorEl: event.currentTarget });
};
handleClose = () => {
this.setState({ anchorEl: null });
};
render() {
const { anchorEl } = this.state;
const { classes } = this.props;
return (
<AppBar className={classes.root}>
<Toolbar>
<Button
variant="contained"
color="secondary"
aria-owns={anchorEl ? "simple-menu" : null}
aria-haspopup="true"
onClick={this.handleClick}
>
Open Menu
</Button>
<Menu
id="simple-menu"
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={this.handleClose}
PopoverClasses={{
paper: classes.menu
}}
>
<MenuItem onClick={this.handleClose}>Profile</MenuItem>
<MenuItem onClick={this.handleClose}>My account</MenuItem>
<MenuItem onClick={this.handleClose}>Logout</MenuItem>
</Menu>
</Toolbar>
</AppBar>
);
}
}
const styles = {
root: {
height: 100
},
menu: {
position: "relative",
top: 100
}
};
export default withStyles(styles)(SimpleMenu);
Here, my navbar is of a fixed height, and when you press the menu button, I want the menu button to open below the nav bar.
To do this - I've added relative styling to the menu popover, and this style is applied to the popover paper - but the inline style that material applies to the popover takes over and it doesn't work.
How am I meant to style this?
A year has passed, anyway. Add styles with PaperProps in this way.
Here is link
PaperProps={{
style: {
marginTop: "40px"
}
}}

Resources