How to use anchorEl with styled() in MUI?

Viewed 371

I'm trying to anchor a popover component to a button component. The problem is that this doesn't seem to work if the button is styled using styled() (I'm using emotion).

This code causes the following warning: MUI: The `anchorEl` prop provided to the component is invalid.

Because anchorEl is invalid the popover will simply postion itself on the top left corner of the screen.

import { useState } from "react";
import { styled } from "@mui/material/styles";
import Popover from "@mui/material/Popover";
import Button from "@mui/material/Button";

export default function BasicPopover() {
  const [anchorEl, setAnchorEl] = useState(null);

  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const open = Boolean(anchorEl);

  const StyledButton = styled((props) => <Button {...props} />)(
    ({ theme }) => ({
      //some styling
    })
  );

  return (
    <div>
      <StyledButton
        variant="contained"
        onClick={handleClick}
      >
        Open Popover
      </StyledButton>
      <Popover open={open} anchorEl={anchorEl} onClose={handleClose}>
        The content of the Popover.
      </Popover>
    </div>
  );
}

I found a slightly different approach using refs here, but I couldn't figure out how to make it work with styled() either.

I'm still rather new to react so please be gentle.

1 Answers

I don't know why, but if you move the styled() out of the main component it works.

const StyledButton = styled((props) => <Button {...props} />)(
    ({ theme }) => ({
      //some styling
    })
  );

export default function BasicPopover() {
  //[...]
}
Related