click-to-copy.component.jsx 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import React, { useRef, useState } from "react";
  2. export default ({ text }) => {
  3. const textareaRef = useRef(null);
  4. const [hovered, setHovered] = useState(false);
  5. const [copied, setCopied] = useState(false);
  6. const copyText = () => {
  7. textareaRef.current.select();
  8. document.execCommand("copy");
  9. setCopied(true);
  10. };
  11. return (
  12. <div
  13. style={{
  14. position: "relative",
  15. display: "flex",
  16. justifyContent: "center",
  17. }}
  18. >
  19. <span
  20. style={{ borderBottom: "1px dotted black" }}
  21. onClick={copyText}
  22. onMouseOver={() => setHovered(true)}
  23. onMouseOut={() => {setHovered(false); setCopied(false)}}
  24. >
  25. {text}
  26. </span>
  27. <span
  28. style={{
  29. display: hovered ? "block" : "none",
  30. backgroundColor: "black",
  31. color: "#fff",
  32. textAlign: "center",
  33. padding: "1px 5px",
  34. borderRadius: "8px",
  35. position: "absolute",
  36. zIndex: 1,
  37. top: "-100%",
  38. whiteSpace: "nowrap",
  39. }}
  40. >
  41. {copied ? "Copied!" : "Click to Copy"}
  42. </span>
  43. <textarea
  44. ref={textareaRef}
  45. style={{ position: "absolute", top: "-1000px" }}
  46. value={text}
  47. readOnly
  48. />
  49. </div>
  50. )
  51. }