Skip to content
Advertisement

Add Tooltip over a button

I’m trying to create a button which copies into clipboard content from variable using TypeScript and Material-UI. I tried this:

const [copySuccess, setCopySuccess] = useState('');

const copyToClipBoard = async (text: string) => {
    try {
        await navigator.clipboard.writeText(copyMe);
        setCopySuccess('Copied!');
    } catch (err) {
        setCopySuccess('Failed to copy!');
    }
};

Button to call above code:

<Button                                    
    onClick={() => copyToClipBoard('some text to copy')}
>
    Copy Url
</Button>

Do you know how I can add Tooltip https://mui.com/components/tooltips/ over the button to display message for successful copy when the text is copied?

Advertisement

Answer

You can use the controlled version of the MUI tooltip to manually open and close the tooltip on some event.

The updated code could be something like below to show and hide the tooltip.

import * as React from "react";
import Button from "@mui/material/Button";
import Tooltip from "@mui/material/Tooltip";

export default function ControlledTooltips() {
  const [open, setOpen] = React.useState(false);
  const [copyFeedback, setCopyFeedback] = React.useState("");
  const handleClose = () => {
    setOpen(false);
  };

  const copyToClipBoard = async (text) => {
    try {
      await navigator.clipboard.writeText(text);
      setCopyFeedback("Copied Successfully");
      setOpen(true);
    } catch (err) {
      console.log("INSIDE ", { open }, err);
      setCopyFeedback("Failed to copy. Please check browser persmissions");
      setOpen(true);
    }
  };

  return (
    <Tooltip
      open={open}
      onClose={handleClose}
      title={copyFeedback}
      leaveDelay={500}
    >
      <Button onClick={() => copyToClipBoard("Text to Copy")}>
        Controlled
      </Button>
    </Tooltip>
  );
}

sandbox

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement