javascriptreactjstypescriptmaterial-uipopper.js

MUI popper always on screen


I want to create chat bot in MUI popper with ref in button in app head bar. When I open popper and scroll down page and hide app bar, I want to see popper. How to do it?

I tried preventOverflow, but popper hides during scroll with button.

<Popper
  placement="bottom"
  modifiers={[
    {
      name: 'preventOverflow',
      enabled: true,
      options: {
        altAxis: true,
        altBoundary: true,
        tether: true,
        rootBoundary: 'document',
        padding: 8,
      },
    },
  ]}
>

Solution

  • You can set the position of the anchor element (the button) to fixed. This will make the button stay in the same place relative to the viewport, even when you scroll down the page and hide the app bar. The popper will then follow the button and stay visible as well.

    For example:

    <IconButton
      onClick={handleClick}
      ref={popperRef}
      sx={{ position: "fixed", bottom: 50, right: 50 }}
    >
      <ChatIcon />
    </IconButton>
    <TextField variant="outlined" size="small" />
    <Popper open={open} anchorEl={popperRef.current}>
      <Box sx={style}>
        <Typography variant="h6" component="h2">
          Text in a modal
        </Typography>
        <Typography sx={{ mt: 2 }}>
          Duis mollis, est non commodo luctus, nisi erat porttitor ligula.
        </Typography>
        <Button onClick={handleClose}>Close</Button>
      </Box>
    </Popper>
    

    You can see the whole example here.