Home > Software design >  Dismiss Material UI Popper after a few seconds automatically
Dismiss Material UI Popper after a few seconds automatically

Time:11-09

I want this popper to show when the "copy link" button is clicked to let the user know that it has been copied, but then disappear on its own after a second or two. Here is the code for the popper

import * as React from 'react';
import Box from '@mui/material/Box';
import Popper from '@mui/material/Popper';

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

  const handleClick = (event) => {
    setAnchorEl(anchorEl ? null : event.currentTarget);
  };

  const open = Boolean(anchorEl);
  const id = open ? 'simple-popper' : undefined;

  return (
    <div>
      <button aria-describedby={id} type="button" onClick={handleClick}>
        Copy Link
      </button>
      <Popper id={id} open={open} anchorEl={anchorEl}>
        <Box sx={{ border: 1, p: 1, bgcolor: 'background.paper' }}>
          Link Copied
        </Box>
      </Popper>
    </div>
  );
}

CodePudding user response:

You might be able to do something with setTimeout in handleClick.

Try modifying handleClick like so:

const handleClick = (event) => {
    setAnchorEl(anchorEl ? null : event.currentTarget);
    setTimeout(() => setAnchorEl(null), 3000);
};
  • Related